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:
- you should have 2 main tables , pivot table: user, contact , user_has_contact
- user_has_contact should content 2 rows: user_id , contact_id
- create fks in both tables
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;
- map tables , generate entities. can using reverse engineering. see documentation
- you should have inside user.php getter (also setter) retrieving associated contacts.
Comments
Post a Comment