laravel whereExists使用

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
) 
posted @ 2023-01-07 13:51  pine007  阅读(900)  评论(0)    收藏  举报