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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:00:23  来源:igfitidea点击:

laravel eloquent relationship with and where clause based on foreign column

phplaraveleloquent

提问by 001221

Hi I want to retrieve my projectsheld in a db which are owned by an auth userwho 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 queryreturns nameyou 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();