laravel雄辩的关系和where子句基于外国专栏

001*_*221 10 php laravel eloquent

嗨,我想要检索我projects所拥有的数据库,这些数据库由auth拥有,user他也创建clients(他们有许多项目和任务)和tasks(属于项目,任务和用户).

我想检索状态表中未标记为已关闭的所有任务,我知道这个ID是2,我可以这样检索:

public function getOpenProjects() {

    return \Project::with(['clients', 'tasks', 'status'])
        ->where('status_id', '!=', '2')
        ->whereUserId(Auth::user()->id)
        ->get();
}
Run Code Online (Sandbox Code Playgroud)

但是如何更改此选项以查询状态表中的列,即该表中的名称列?

The*_*pha 36

你可以试试这个:

$value = 'someName';
Project::with(['clients', 'tasks', 'status' => function($q) use($value) {
    // Query the name field in status table
    $q->where('name', '=', $value); // '=' is optional
}])
->where('status_id', '!=', '2')
->whereUserId(Auth::user()->id)
->get();
Run Code Online (Sandbox Code Playgroud)

你也可以尝试这个(只有你想要的query回报才能获取记录name,否则没有):

$value = 'someName';
Project::with(['clients', 'tasks', 'status'])
       ->whereHas('status', function($q) use($value) {
       // Query the name field in status table
       $q->where('name', '=', $value); // '=' is optional
})
->where('status_id', '!=', '2')
->whereUserId(Auth::user()->id)
->get();
Run Code Online (Sandbox Code Playgroud)

  • 我需要-> whereHas()方法来使其正常工作。谢谢! (2认同)

小智 7

你可以试试这个:

Project::with(['clients', 'tasks' => function($q) use($value) {
// Query the name field in status table
    $q->where('status_id', '!=', '2'); 
}])
->whereUserId(Auth::user()->id)
->get();
Run Code Online (Sandbox Code Playgroud)