Degu
Degu

Reputation: 188

Symfony related manytomany object query

I'm trying to query related objects and I have some problems.. Hopefully someone of you can help me out.

So, I have two 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 is following

User_id **** Contact_id

1 ------------ 1
2 ------------ 1
3 ------------ 2
4 ------------ 2

I'm trying to get user_ids related to queried contact_id

I have already 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 and currently I have

$test = $this->getDoctrine()->getRepository('UserBundle:User')->findAll();

twig

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

which gets me contact_id, but how I get user_ids related to it? Thanks for your time!

Upvotes: 0

Views: 115

Answers (1)

viarnes
viarnes

Reputation: 2048

You should be able to access the related many to many entity by doing $user->getContact() or inside twig template {{ user.contact }}. Instead of writting the getter all alone you can follow the next steps:

  1. You should have 2 main tables and a pivot table: user, contact and user_has_contact
  2. user_has_contact should content two rows: user_id and contact_id
  3. Create the 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 the tables and generate the entities. You can do this using reverse engineering. See documentation
  2. You should now have inside User.php the getter (also the setter) for retrieving the associated contacts.

Upvotes: 1

Related Questions