JoeLoco
JoeLoco

Reputation: 2204

This is a Doctrine 2.2 Foreign Key Bug?

My Code:

        $item = new Entity\Item();

        $item->setAccountId($account["id"]);
        $item->setCategory((string)$data->category);
        $item->setRegion((string)$data->region);
        $item->setFlag(0);
        $item->setRank(0);
        $item->setPhone("");
        $item->setEmail("");
        $item->setURL((string)$data->url);
        $item->setTags($tags);

        //var_dump($item);
        //die();

        $this->em->persist($item);
        $this->em->flush();
        $this->em->clear();

Annotation Relationship:

/////////////////////////////////////////////////////////////////////////
// Relations                                                     //
/////////////////////////////////////////////////////////////////////////

/**
* @ManyToOne(targetEntity="Account", inversedBy="items")
* @JoinColumn(name="account_id", referencedColumnName="id")
*/
private $account;

/////////////////////////////////////////////////////////////////////////
// ForeingKey                                                           //
/////////////////////////////////////////////////////////////////////////

/**
 * @Column(type="integer")
 */
protected $account_id;   

If i use old doctrine (2.0) the code work, if i set to 2.2 , code throw this exception:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'account_id' cannot be null

In 2.2 i need to use the Parent entity to insert a Chield entity?

Upvotes: 0

Views: 127

Answers (1)

K. Norbert
K. Norbert

Reputation: 10674

From Doctrine2's point of view, your objects should form an object graph, where foreign keys have no place. Because of this, I find it really weird that you

  • have an attribute_id property which is a foreign key
  • say that it worked in 2.0

I'm not sure how it was in 2.0, but I don't remember having ids of a related object in properties.

So, you should drop the $account_id property, and use $item->setAccount($account), where $account is an object of class Account, in order for Doctrine to correctly handle the relation.

You can also try letting Doctrine generate entity skeletons for you with the command:

php doctrine.php orm:generate-entities /tmp/entites

And check the generated files in /tmp/entities, you will see how should look.

Upvotes: 0

Related Questions