阅读(2324) (0)

Laravel 8 Where Exists 语句

2021-07-07 09:14:26 更新

whereExists 方法允许你使用 where exists SQL 语句。whereExists 方法接收一个 闭包 作为参数,该闭包获取一个查询构建器实例,从而允许你定义放置在 「exists」 字句中的查询:

$users = DB::table('users')
           ->whereExists(function ($query) {
               $query->select(DB::raw(1))
                     ->from('orders')
                     ->whereRaw('orders.user_id = users.id');
           })
           ->get(); 

上述查询将产生如下的 SQL 语句:

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)