php - Symfony related manytomany object query -


i'm trying query related objects , have problems.. of can me out.

so, have 2 manytomany related entity

user entity

/**  * @orm\manytomany(targetentity="contact", inversedby="users")  * @orm\jointable(name="users_contacts")  */ protected $contacts; 

and contact entity

/** * @orm\manytomany(targetentity="user", mappedby="contacts") */ protected $users; 

table: users_contacts following

user_id **** contact_id  1 ------------ 1 2 ------------ 1 3 ------------ 2 4 ------------ 2 

i'm trying user_ids related queried contact_id

i have tried multiple different querybuilder

for example:

return $this->createquerybuilder('u') ->innerjoin('u.contacts', 'c', 'with', 'c.id = :$user_id') ->setparameter('user_id', $user_id); 

but without result , have

$test = $this->getdoctrine()->getrepository('userbundle:user')->findall(); 

twig

{% user in test %}    {{ users.id }} {% endfor %}  

which gets me contact_id, how user_ids related it? time!

you should able access related many many entity doing $user->getcontact() or inside twig template {{ user.contact }}. instead of writting getter alone can follow next steps:

  1. you should have 2 main tables , pivot table: user, contact , user_has_contact
  2. user_has_contact should content 2 rows: user_id , contact_id
  3. create fks in both tables

simple table

create table if not exists `mydb`.`user` (   `id` int not null auto_increment,   `name` varchar(45) null,   primary key (`id`)) engine = innodb;  create table if not exists `mydb`.`contact` (   `id` int not null auto_increment,   `name` varchar(45) null,   primary key (`id`)) engine = innodb;  create table if not exists `mydb`.`user_has_contact` (   `user_id` int not null,   `contact_id` int not null,   primary key (`user_id`, `contact_id`),   index `fk_user_has_contact_contact1_idx` (`contact_id` asc),   index `fk_user_has_contact_user_idx` (`user_id` asc),   constraint `fk_user_has_contact_user`     foreign key (`user_id`)     references `mydb`.`user` (`id`)     on delete no action     on update no action,   constraint `fk_user_has_contact_contact1`     foreign key (`contact_id`)     references `mydb`.`contact` (`id`)     on delete no action     on update no action) engine = innodb; 
  1. map tables , generate entities. can using reverse engineering. see documentation
  2. you should have inside user.php getter (also setter) retrieving associated contacts.

Comments

Popular posts from this blog

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -