php laravel 基于外来列的与和 where 子句的雄辩关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25797216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel eloquent relationship with and where clause based on foreign column
提问by 001221
Hi I want to retrieve my projects
held in a db which are owned by an auth user
who also creates clients
(they have many projects and tasks) and tasks
(belongs to a project and tasks and user).
嗨,我想检索我projects
持有的数据库,该数据库由user
也创建clients
(他们有许多项目和任务)和tasks
(属于项目和任务和用户)的身份验证拥有。
I want to retrieve all tasks that are not marked as closed in the status table, I know the id of this is 2 and I can retrieve this as so:
我想检索状态表中未标记为关闭的所有任务,我知道它的 id 是 2,我可以这样检索:
public function getOpenProjects() {
return \Project::with(['clients', 'tasks', 'status'])
->where('status_id', '!=', '2')
->whereUserId(Auth::user()->id)
->get();
}
But how can I change this to query against a column in the statuses table, i.e. the name column in that table?
但是如何更改它以查询状态表中的列,即该表中的名称列?
回答by The Alpha
You may try this:
你可以试试这个:
$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();
Also you may try this (It will fetch records only if the query
returns name
you want, otherwise none):
你也可以试试这个(它只会在你想要的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();
回答by Md Shahadat Hossain
You may try this:
你可以试试这个:
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();