left join with ActiveRecord (yii2)

二次信任 提交于 2020-03-06 02:37:08

问题


I tried to send SQL request with LEFT JOIN but it doesn't display data from table2 table.

public static function top($limit)
{
    return self::findBySql("
        SELECT * FROM table 1 g1 
        LEFT JOIN table2 s1 
        ON (g1.id = s1.g_id AND s1.id = (
            SELECT MAX(id) 
            FROM table2 s2 WHERE s2.g_id = g1.id
        )) 
        LIMIT :limit", 
    [':limit' => $limit]
    )->all();
}

回答1:


It seems you are adding this function to the model and self represents the model itself.

Yii will not return results from another table and will be limited to the model only if you are calling the find on a model, instead you need to use a db query as below:

    $query = new \yii\db\Query;
    $query->select('*')
            ->from('table 1 g1')
            ->leftJoin('table2 s1', 's1.g_id AND s1.id = (SELECT MAX(id) FROM table2 s2 WHERE s2.g_id = g1.id')  
            ->limit($Limit);
    $command = $query->createCommand();
    $resp = $command->queryAll();



回答2:


The correct SQL query is

SELECT * FROM table 1 g1 
        LEFT JOIN table2 s1 
        ON g1.some_field = s1.some_field

where g1.some_field = s1.some_field are the fields that define the join.




回答3:


I have working code something like...:) with user and user_friend_list

                                 $query = new Query;
                                 $query  ->select(['user.id AS user_id', 'user_friend_list.id'])  
                                        ->from('user')
                                        ->innerJoin('user_friend_list', 'user.email = user_friend_list.email');

                                $command = $query->createCommand();
                                $data = $command->queryAll();
                                foreach($data as $datakey)
                                {
                                    //echo $datakey['id'];
                                    $friendfind = UserFriendList::findOne($datakey['id']);
                                    $friendfind->is_app_using_user_id=$datakey['user_id'];
                                    $friendfind->save();
                                }


来源:https://stackoverflow.com/questions/28971501/left-join-with-activerecord-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!