Вопрос

Please help me want to left join two table in Codeigniter with Orm docrtrine 2 libray.

Это было полезно?

Решение

Doctrine entity model doesn't give association for one to many and vice-versa. To allow these feature you have to update your entities with valid association. Below is an example for such two tables which contains user information in users table and there favorite meals in UserFavoriteMeals

For Left JOIN update needed in both entities for association explained below :

In user entity add onetomany association of UserFavoriteMeals where mappedby is the key on basis of which association happens in db.

 /**
     * @var \Entity\UserFavoriteMeals
     *
     * @OneToMany(targetEntity="Entity\UserFavoriteMeals", mappedBy="userid" )
     *  @JoinColumns({
     *   @JoinColumn(name="id", referencedColumnName="userId", nullable=true)
     * })
     */

    private $UserFavoriteMeals;

Simillary, Put manyToOne association in UserFavoriteMeals entity

/**
 * @var \Entity\Users
 *
 * @ManyToOne(targetEntity="Entity\Users")
 * @JoinColumns({
 *   @JoinColumn(name="userId", referencedColumnName="id", nullable=true)
 * })
 */
private $userid;

In these manner we have to manage associations for Left JOIN, now simply write a Left JOIN query in below format :

            $left_query = $this->em->createQuery("SELECT fm,u FROM Entity\userFavoriteMeals fm LEFT JOIN fm.userid u WHERE fm.userId = 231 ")->getArrayResult(); 
        print_r($left_query);

        $left_query_inverse = $this->em->createQuery("SELECT u,fm FROM Entity\Users u LEFT JOIN u.UserFavoriteMeals fm WHERE u.id = 4")->getArrayResult(); 
        print_r($left_query_inverse);

Другие советы

First you need to integrate Doctrine into CodeIgnitor.

http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html

This is how you use custom query to left join two tables in Doctrine.

<?php
$query = $em->createQuery('SELECT u.id, a.id as article_id FROM CmsUser u LEFT JOIN u.articles a');
$results = $query->getResult(); // array of user ids and every article_id for each user

More on custom query :- http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html

If you want DQL way, which is preferred, it should be something like this.

$qb->select('u')
       ->from('Entity_User', 'u')
       ->leftJoin('u.profile','p')
       ->leftJoin('a.user_details','ud')
       ->where('u.id = :id')
       ->setParameter('id','100')
       ->getQuery();

More on DQL :- http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html

I hope this helps, Cheers!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top