laravel eloquent ->whereHas - 编写你自己的存在(子查询)

问题描述 投票:0回答:3

Laravel Eloquent

->whereHas()
使用
exists()
子查询 - https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html - 为了返回您的结果。

我想编写自己的子查询,但我不知道如何告诉 Eloquent -> 它在哪里。

如果我这样做:

$query->where( DB::raw(' exists( subquery ) ')

Laravel 将子查询写为:

where exists( subquery ) is null

所以我只是想知道什么

$query->method()
可以用来向'where'语句添加一个exists()子查询。子查询与 laravel 生成的类型相同,但写出来了:

... and exists ( select * from `tbl` inner join `assets` on `custom_assets`.`id` = `tbl`.`asset_id` where `assets`.`deleted_at` is null and `users`.`id` = `assets`.`client_id` and `field_id` = ? and (`value` = ? and `assets`.`deleted_at` is null )
php mysql laravel eloquent exists
3个回答
2
投票

使用

whereRaw()

$query->whereRaw('exists( subquery )')

1
投票

阅读此处的说明

您可以在那里找到此代码示例。您还可以在 whereHas 中为自定义查询添加闭包。

// Retrieve all posts with at least one comment containing words like foo%
$posts = App\Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

0
投票

请在文档中寻找答案: https://laravel.com/docs/11.x/queries#where-exists-clauses

$users = DB::table('users')
           ->whereExists(function (Builder $query) {
               $query->select(DB::raw(1))
                     ->from('orders')
                     ->whereColumn('orders.user_id', 'users.id');
           })
           ->get();
© www.soinside.com 2019 - 2024. All rights reserved.