将SQL查询转换为laravel雄辩

时间:2020-06-13 19:25:21

标签: sql laravel eloquent

我有这个SQL RAW查询:

select * from table_a where (select id from table_b where table_a.table_b_id = table_b.id and table_b.code = '02') = table_a.table_b_id  and user = '123456'  order by id desc limit 1

我需要雄辩地转换为Laravel。我已经尝试了几个小时了

2 个答案:

答案 0 :(得分:0)

这显然可行

$tran = Table_A::join('table_b', function ($join) {
    $join->on('table_a.table_b_id', '=', 'table_b.id')
        ->where('table_b.code', '02');
})->where('user', '123456')
   ->orderBy('table_a.id', "DESC")->limit(1)
    ->get();

答案 1 :(得分:0)

如果要使用Eloquent,则必须创建模型和关系。弄清楚这两个表是如何连接的:hasOne,hasMany,hasManyThrough等。https://laravel.com/docs/7.x/eloquent-relationships

创建模型及其关系时,您的查询将是雄辩的。