user2930924 user2930924 - 6 months ago 22
PHP Question

Doctrine - ManytoMany Filter Result

I need to get a filter result from a many to many relationship in doctrine.

Class Users extends RecordItem {
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
**/

protected $id;
/**
* @ManyToMany(targetEntity="Company")
* @JoinTable(name="users_join_company",
* joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="company_id", referencedColumnName="id")}
* )
*/
protected $companys;

/**
* @Column(type="string", length=100)
* @var string
*/
protected $username;
//edit - > added array collection - forgotten
public function __construct() {
$this->companys = new ArrayCollection();
}
}

Class Company extends Recorditem {

/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
**/
protected $id;

/**
* @Column(type="string", length=100)
* @var string
*/
protected $company_name;
}


so far I'm only able to query all company from the following code, is there a proper way to add a filter? example: there are 3 company in array collection, would want to return one with specify company "id"

$user = $entityManager->getRepository('Users')->findOneBy(['id'=>1]);

$companys = $user->companys; // hope to return only company with the id 1

foreach($companys as $company){
echo $company->company_name;
}

Answer

If you want to filter a collection, use ArrayCollection ...

http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html

Example :

// I guess companies is an ArrayCollection
$myDesiredCompanies = $companies->filter(function (Company $entry) {
    return ($entry->getId() == 1);
});

It will filter the collection and return a new Collection with your desired results