左连接ActiveRecord(yii2)

时间:2015-03-10 18:33:57

标签: activerecord yii yii2

我尝试使用LEFT JOIN发送SQL请求,但它不显示来自table2表的数据。

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();
}

3 个答案:

答案 0 :(得分:6)

您似乎将此功能添加到模型中, self 表示模型本身。

Yii不会返回另一个表的结果,只有在模型上调用find时才会限制模型,而是需要使用db查询,如下所示:

    $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();

答案 1 :(得分:0)

正确的SQL查询是

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

其中g1.some_field = s1.some_field是定义连接的字段。

答案 2 :(得分:0)

我的工作代码类似...... :) with user和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();
                                }