WhereNotExists Laravel Eloquent

≯℡__Kan透↙ 提交于 2020-01-22 19:31:09

问题


Little bit of trouble with the eloquent framework for laravel.

I need to replicate a query like this :

SELECT *
FROM RepairJob
WHERE NOT EXISTS (SELECT repair_job_id
    FROM DismissedRequest
    WHERE RepairJob.id = DismissedRequest.repair_job_id);

Right now I have

 $repairJobs = RepairJob::with('repairJobPhoto', 'city', 'vehicle')->where('active', '=', 'Y')->whereNotExists('id', [DismissedRequest::all('repair_job_id')])->get();

Anyone an idea? I need to get all the repairjobs where there is no record for in the dismissed requests table

I get this error when using the query above

Argument 1 passed to Illuminate\Database\Query\Builder::whereNotExists() must be an instance of Closure, string given

回答1:


Try doesntHave() method. Assuming 'dismissedRequests' as relation name in RepairJob model.

$jobs = RepairJob::with('repairJobPhoto', 'city', 'vehicle')
    ->where('active', 'Y')->doesntHave('dismissedRequests')->get();



回答2:


Try this:

$repairJobs = RepairJob::with('repairJobPhoto', 'city', 'vehicle')
              ->where('active', '=', 'Y')
              ->whereNotExists(function($query)
                {
                    $query->select(DB::raw(1))
                          ->from('DismissedRequest')
                          ->whereRaw('RepairJob.id = DismissedRequest.id');
                })->get();


来源:https://stackoverflow.com/questions/38572706/wherenotexists-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!