'Doctrine Querying on a Relationship
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!
Solution 1:[1]
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]);
Solution 2:[2]
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]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harvey Dent |
| Solution 2 | martonmisley |
