Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DQL query with joining table and two join

I have 2 entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\ManyToMany(targetEntity="Myapp\UserBundle\Entity\Group")
     * @ORM\JoinTable(name="user_groups",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
     * )
     */
    protected $groups;

    ...
}

and

/**
 * @ORM\Entity(repositoryClass="Myapp\UserBundle\Repository\GroupRepository")
 * @ORM\Table(name="groups")
 */
class Group
  ...

I cant find a way to create a DQL query which results SQL like this:

SELECT g.name, g.id, count( u.id )
FROM users u
LEFT JOIN user_groups ug ON u.id = ug.user_id
RIGHT JOIN groups g ON g.id = ug.group_id
GROUP BY g.id

I tried and failed whith:

$this->getEntityManager()
    ->createQuery('
        SELECT g.id, g.name, count(u.id) as usercount FROM MyappUserBundle:User u
        JOIN u.groups g
        GROUP BY g.id'
    );

since the result not contains the groups that has no user.

like image 900
user1063963 Avatar asked Dec 16 '11 13:12

user1063963


People also ask

How do I join two joined tables in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

Can we use two joins in single query?

Multiple joins can be described as a query containing joins of the same or different types used more than once, thus giving them the ability to combine multiple tables.

Can we join two tables on two columns SQL?

The SQL JOIN is one of the basic tools for data analysts working with SQL. Relational databases are built in a way such that analytical reports usually require combining information from several tables. You'll be joining tables, sometimes by one column and other times by two or more columns.

How can I join more than two tables in SQL?

In SQL Server, you can join more than two tables in either of two ways: by using a nested JOIN , or by using a WHERE clause. Joins are always done pair-wise.


1 Answers

It's a ManyToMany relation, don't event try to join on the relation table, only the related entity... Then, you were right with the RIGHT JOIN ... for a SQL query, but Doctrine automatically defines the jointure type from the FROM clause.

In DQL, only defined relations are managed by jointures, so you don't need USE or ON clauses...

What about this one ?

SELECT g.name, g.id, count( u.id )
FROM groups g
JOIN users u
GROUP BY g.id
like image 112
AlterPHP Avatar answered Sep 23 '22 12:09

AlterPHP