将sql查询转换为laravel eloquent

wa7juj8i  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(358)

我有一个sql原始查询:

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

我需要转换成拉雷维尔能言善辩。我已经试了好几个小时了

mkh04yzy

mkh04yzy1#

这显然奏效了

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

fv2wmkja2#

如果你想使用雄辩你必须建立模型和关系。弄清楚这两个表是如何连接的:hasone,hasmany,hasmanythrough等等。https://laravel.com/docs/7.x/eloquent-relationships
当您创建模型及其关系时,您的查询将是雄辩的。

相关问题