Laravel 5.8 foreign key migration error - "Foreign key constraint is incorrectly formed" - foreign-keys

I need to create foreign key to join table books with table users. I know that user_id column has to be the same type also unsigned if origin col is unsigned but it should be ok. Both table are bigint(20) unsigned. But I am getting an error: "Foreign key constraint is incorrectly formed"
Here is the migration code:
public function up()
{
Schema::table('books', function (Blueprint $table) {
$table->unsignedBigInteger('user_id')->nullable()->index()->after('id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('SET NULL')->onUpdate('CASCADE');
});
}
and here is the users table migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Can somebody tell me please where is the problem? Thanks a lot.

The problem was caused by default MariaDB MyIsam engine for tables. So I needed to restart db with new my.ini which defaults to InnoDB and then migrate all tables again.

Related

Cannot query fromSql method with Entity Framework Core

I started a asp.net core project, using EF core 2.0.1.
I was able to migrate a database successfully to the project and generated partial class as follows
public partial class ManagementContext : DbContext
{
public virtual DbSet<Result> Results { get; set; }
}
I'm able to connect to the database and get db and get the all records in the db by assigning:
var results = dbContext.Results.ToList();
However when trying to assign by .fromSql() method i get error:
invalidlidOperationException: 'The required column 'Id' was not present in the results of a 'FromSql' operation.'
The errors is received in both of the following queries (get_results is a stored procedure that returns records of Result:
var resultsThroughRawQuery = dbContext.Results.FromSql("select * from dbo.Results").ToList();
var resultsThroughStoredProcedure = dbContext.Results.FromSql("EXEC get_results").ToList();
Result indeed has an Id columnm which is the key.
Is there something I miss here?

How to persist only one end of a relationship and the other one only if the entity doesn't exist?

I have a complex/nested object created by automatic hydration from Zend\Form data. Now I want to save it with Doctrine 2. The best case would be just one persist(...) and one flush(...) call on the top level. But it doesn't work like this. So now I have following problem:
There are objects User and Order. The relationship is 1:n (so, 1 User has n Orders). The User exists already. When a User Joe tries to save more than one Order (e.g. its second order), an error occurs:
A new entity was found through the relationship '...\Order#user' that was not configured to cascade persist operations for entity: ...\User#000000003ba4559d000000005be8d831. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement '...\User#__toString()' to get a clue.
Allright, I add cascade={"persist"} (though it doesn't make sense here, but anyway, just to try it out):
class Order
{
...
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="User", cascade={"persist"})
*/
protected $user;
...
}
Now it works, if the given User doesn't exist: An Order and a User is created.
But if the User exists, an error occurs:
An exception occurred while executing 'INSERT INTO user (username, role, created, updated) VALUES (?, ?, ?, ?)' with params ["myusername", "member", null, null]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'myusername' for key 'username_UNIQUE'
How to handle the saving so, that the User only gets saved, if it doesn't exist yet?
The solution is to persist the User before saving the referencing entity. If it doesn't exist yet, it needs to be created (persisted and flushed) first:
$user = $this->entityManager->getRepository(User::class)->findOneBy(
['username' => $dataObject->getUser()->getUsername()]
);
if (! $user) {
$this->entityManager->persist($dataObject->getUser());
$this->entityManager->flush($dataObject->getUser());
$user = $this->entityManager->getRepository(User::class)->findOneBy(
['username' => $dataObject->getUser()->getUsername()]
);
}
$dataObject->setUser($user);
$this->entityManager->persist($dataObject);
$this->entityManager->flush();
And the cascade={"persist"} should not be used, since it actually doesn't make sense in this case.
EDIT
Or even easier:
$user = $this->entityManager->getRepository(User::class)->findOneBy(
['username' => $dataObject->getUser()->getUsername()]
);
if ($user) {
$dataObject->setUser($user);
} else {
$this->entityManager->persist($dataObject->getUser());
}
$this->entityManager->persist($dataObject);
$this->entityManager->flush();

Drop column in Dynamo DB table

I've been looking through the AWS Dynamo DB documentation and the Amazon Dynamo interface and it seems like there's no way to remove a column from a table, outside of deleting the entire table with it's contents and starting over, is that true?
If so, why would Amazon not support this?
Try removing all data from that column, it will automatically remove that column.
Using document client with javascript, we can do this:
const paramsUpdate = {
TableName: tableName,
Key: { HashKey: 'hashKey' },
UpdateExpression: 'remove #c ',
ExpressionAttributeNames: { '#c': 'columnName' }
};
documentClient.update(paramsUpdate, (errUpdate) => {
if (errUpdate) log.error(errUpdate);
});
In here we set UpdateExpression with remove sentence
There is a REMOVE action in the DynamoDB API.
DynamoDB does not have a schema definition, and so there is no such thing as a "column". It also means there is no way to delete all attributes with the same name without iterating over each record.
A solution I recommend is to keep these attributes, and to make your code refer to that same data using a fresh attribute name.
For example, attribute content could become content_v2. It might not look so clean, but it's cheap, quick and your old data would be backed up.
Setting all instances of the column value to null clears the column.
In C#, this method does the trick using the persistence framework:
static void RemoveColumn()
{
var myItems = context.ScanAsync<MyObjectType>(null).GetRemainingAsync().Result;
// Foreach item, update
myItems.ForEach(myObject =>
{
myObject.UnwantedColumn = null;
context.Save(myObject);
});
}
Just remove all the data for that one column. On my end, it automatically refreshed, might have to refresh the page.

Symfony 2.1 - FPNTagBundle - add a Tag bug?

I have installed FPNTagBundle via composer.
$tagArray=array('uno','due');
$tagManager = $this->get('fpn_tag.tag_manager');
$tagsObj = $tagManager->loadOrCreateTags($tagArray);
$tagManager->replaceTags($tagsObj,$entity);
$em->persist($entity);
$em->flush();
I get this error that avoid tag to persist:
An exception occurred while executing 'INSERT INTO Tag (name, slug,
created_at, updated_at) VALUES (?, ?, ?, ?)' with params
{"1":null,"2":"uno","3":null,"4":null}:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name'
cannot be null 500 Internal Server Error - DBALException
It's seems a problem calling $tag = parent::createTag($name); in line35 of TagManager.php
Any ideas?
v.
I came across the same issue in my project.
The problem was that the Tag entity prevented the execution of the constructor in the BaseTag (FPN\TagBundle\Entity\Tag) class. I am pretty sure that your Tag class has its own constructor and you do not call the parent one, which sets the name attribute missing in your entity.
Here is an example custom Tag class which calls the parent constructor to set the name:
use FPN\TagBundle\Entity\Tag as BaseTag;
class Tag extends BaseTag
{
protected $tagging;
public function __construct($name = null)
{
parent::__construct($name);
$this->tagging = new ArrayCollection();
}
}

composite and foreign keys as primary key doctrine 2 + zend framework 2

I have been wondering why my mappings and the controller actions are not working. For this I need to refer to my previous post, where I have described my entities and database schema, which can be found here. I need to start a new post since there were no further updates and I thought this the only way to get attention of the Doctrine + Zend Pros.
As described in my previous post, I have a Zend Form, the user can enter teamId and teamName, further he has the choice to select multiple players from the drop down list on the form and can allocate players to the team. So basically that is my goal to achieve with Doctrine and Zend. For that I wrote my entities described in the previous post and right now I want to add the code from my controller to persist the entities.
Controller:
public function addAction()
{
$form = new TeamForm($this->getEntityManager());
$form->get('submit')->setAttribute('value', 'Add');
$request = $this->getRequest();
if ($request->isPost())
{
$team = new Team();
$player = new Player();
$teamPlayers = new TeamPlayer();
$form->setInputFilter($typeset->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$team->populate($form->getData());
$teamPlayers->setPlayer($player);
$teamPlayers->setTeam($team);
$this->getEntityManager()->persist($teamPlayers);
$this->getEntityManager()->flush();
//Reroute to the index page once the data is successfully added
}
}
//return form array
return array(
'form' => $form
);
}
So that is basically what Im doing in my controller to save the entities into two tables (team Table and teamPlayer Table), as already the player Table is populated with data. So I want to add players to the team and assign that values in these two tables.
Right now I can see my form and when I enter the data and press submit nothing is happening, i can see the form with no action. When the data is successfully saved into the database then I reroute it to the index page which is not happening.
Any help would be appreciated, to point out the error Im making either in mapping section or in the controller side.
The official documentation especially from Doctrine 2 is too global and is particulary not that clear for my requirement.
let's try to solve it by updating this answer by steps :
step 1 :
your words implied to me that , you might have some issues in from validation , so lets check if you are passing this $form->isValid()
if ($form->isValid())
{
$team->populate($form->getData());
$teamPlayers->setPlayer($player);
$teamPlayers->setTeam($team);
$this->getEntityManager()->persist($teamPlayers);
$this->getEntityManager()->flush();
//Reroute to the index page once the data is successfully added
}else{
var_dump($form->getMessages());
}
I can also suggest you to use doctrine commandline : doctrine orm:validate-schema , this command will help you to check if your entity mapping is ok plus your database mapping is also okay , i see it as handy to to debug your doctrine2 entity 
ps : I havn't read your entities in depth yet