Reputation: 650
I've broken my head trying to set annotations for my 2 entities in order to use join tables.
I have 2 tables: user and cart.
Cart contains user ids with products which users selected.
1 user can have many products, so it's a ManyToOne relationship.
When I tried to set up the associations I tried a lot of different things and none of them worked. Now I'm having this:
// ---------------- USER CLASS ------------------- //
/**
* @ORM\Entity
* @ORM\Table(name="user", indexes={@ORM\Index(name="firstname_idx", columns={"firstname"}), @ORM\Index(name="lastname_idx", columns={"lastname"}), @ORM\Index(name="email_idx",columns={"email"})})
*/
class User
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="string", length=100)
*/
public $firstname;
/**
* @ORM\Column(type="string", length=100)
*/
public $lastname;
/**
* @ORM\Column(type="string", length=100, nullable=true)
*/
public $email;
/**
* @ORM\OneToMany(targetEntity="Cart", mappedBy="users")
**/
public $cart;
public function __construct() {
$this->cart = new ArrayCollection();
}
//...
And the Cart class:
/**
* @ORM\Entity
* @ORM\Table(name="cart")
*/
class Cart {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="integer", nullable=true)
*/
public $user_id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="cart")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
**/
public $users;
public function __construct() {
$this->users = new ArrayCollection();
}
When I execute a query with join of these tables I receive the message: "[Semantical Error] line 0, col 84 near 'u': Error: Class Cart has no association named User"
My query looks like this:
$q = $db->em->createQueryBuilder()
->select('c.*, u.*')
->from("Application\Entity\Cart","c")
->join("c.Application\Entity\User","u")
->getQuery();
What am I doing wrong? How to set the annotaions? I'll appreciate any help.
Upvotes: 0
Views: 198
Reputation: 650
Well, I figured it out by myself and again I'm answering my own question.
I spent several days on trying to fix the annotations. But the real problem was in the query.
I was trying to join entities as I was always doing it in Doctrine1. But in Doctrine2 when you join tables you have to join with the parameter you defined in the entity as the join parameter. So in my case it would be:
$q = $db->em->createQueryBuilder()
->select('c, u')
->from("Application\Entity\Cart","c")
->join("c.users","u")
->getQuery();
That was tricky for one that is used to work with doctrine1...
Upvotes: 2