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

时间:2014-09-11 21:27:45

标签: php laravel eloquent

您好我想要检索一个数据库中保存的projects,该数据库由一个身份验证user拥有,同时创建clients(他们有很多项目和任务)和{{1} (属于项目,任务和用户)。

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

tasks

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

2 个答案:

答案 0 :(得分:27)

你可以试试这个:

$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();

此外,您可以尝试此操作(仅当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();

答案 1 :(得分:2)

你可以试试这个:

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();