左加入 ActiveRecord (yii2)

left join with ActiveRecord (yii2)

我尝试使用 LEFT JOIN 发送 SQL 请求,但它不显示来自 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();
}

您似乎正在将此函数添加到模型中,self 代表模型本身。

Yii 不会 return 来自另一个 table 的结果,并且仅当您在模型上调用查找时才会限于模型,而不是您需要使用如下的数据库查询:

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

正确的SQL查询是

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

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

我有类似的工作代码...:) 与用户和 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();
                                }