Home > Blockchain >  Doctrine Querying on a Relationship
Doctrine Querying on a Relationship

Time:02-24

I am using doctrine and created a User entity with a OneToMany relation on Meal

User class

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 */
class User

    /**
    * @ORM\OneToMany(targetEntity=Meal::class, mappedBy="user")
    */
    private $meals;

Meal class

/**
 * @ORM\Entity(repositoryClass=MealRepository::class)
 */
class Meal
{

/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="meals")
* @ORM\JoinColumn(nullable=false)
*/
private $user;

    /**
    * @ORM\Column(type="date")
    * @Groups({"read:softdiet:item"})
    */
    private $day;

I want to find meals from a specific user and date.

I tried

$meal = $entityManager->getRepository('App\Entity\Meal')->findBy(['user.id' => $userId, 'date' => $date]);

but I get an error: "Unrecognized field: user.id'"

Help me please!

CodePudding user response:

In the findBy method, you do not have access to the properties of the User entity, since you are searching in the Meal entity. You can do it like this:

$meal = $entityManager->getRepository('App\Entity\Meal')->findBy(['user' => $userId, 'date' => $date]);

CodePudding user response:

With ORM you use objects and properties, not column names, so in your case it's:

$meal = $entityManager
    ->getRepository('App\Entity\Meal')
    ->findBy(['user' => $user, 'date' => $date]);
  • Related