Linked Questions

Popular Questions

I have two entities (User and Product) with a OneToMany relationship. I want to retrieve all Product entities related to a specific User filtering them by a field called "finished". I will post the relevant information of those entities:

User Entity:

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="user")
     */
    private $products;


    ....

Product Entity:

/**
 * @ORM\Entity(repositoryClass="App\Repository\Productepository")
 */
class Product
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="products")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    /**
     * @ORM\Column(type="boolean")
     */
    private $finished;


    ....

I am using the following code to filter my products, but is there any other more efficient way to do it?

$user = $this->getUser();
$products = $user->getProducts();
$filtered = [];

foreach ($products as $product){
    if(!$product->getFinished()){
        $filtered[] = $product;
    }
}

Thanks for your help

Related Questions