用ActiveRecord(yii2)左连接 [英] left join with ActiveRecord (yii2)

查看:1674
本文介绍了用ActiveRecord(yii2)左连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送SQL请求,LEFT JOIN,但它不会显示从数据表2 表。

 公共静态函数顶部($限制)
{
    回归自我:: findBySql(
        SELECT * FROM表1 G1
        LEFT JOIN表2 S1
        ON(g1.id = s1.g_id和s1.id =(
            SELECT MAX(ID)
            从表2 S2,其中s2.g_id = g1.id
        ))
        LIMIT:限制,
    [':限制'=> $极限]
    ) - >所有的();
}
 

解决方案

看来你要添加这个功能模型和再presents模型本身。

Yii的将不从另一个表中返回结果,并只限于如果您呼叫的找到一个模型的模型,而不是你需要使用如下所示的数据库查询:

  $查询=新\警予\ DB \查询;
    $查询 - >选择(*)
             - 肽从('表1 G1')
             - > leftJoin(表2 S1','s1.g_id及s1.id =(SELECT MAX(ID)从表2 S2,其中s2.g_id = g1.id')
             - >限制($限制);
    $命令= $查询 - > createCommand();
    $ RESP = $命令 - > queryAll();
 

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

解决方案

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

这篇关于用ActiveRecord(yii2)左连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆