php laravel基于foreign column与where子句的关系

7xzttuei  于 2023-09-29  发布在  PHP
关注(0)|答案(4)|浏览(118)

你好,我想检索我的projects在一个数据库中持有的身份验证user谁也创建clients(他们有许多项目和任务)和tasks(属于一个项目和任务和用户)。
我想检索状态表中未标记为已关闭的所有任务,我知道此任务的ID为2,因此可以检索此任务:

public function getOpenProjects() {

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

但是我怎样才能改变它来查询状态表中的一列呢?该表中的名称列?

dzjeubhm

dzjeubhm1#

你可以试试这个:

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

ao218c7q2#

你可以试试这个:

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

j7dteeu83#

现在,您可以使用 * whereRelation *

public function getOpenProjects() {

return Project::with(['clients', 'tasks', 'status'])
             ->whereRelation('status', 'name', '!=', '2')        
             ->whereUserId(Auth::user()->id)
             ->get();
}
vd2z7a6w

vd2z7a6w4#

如果你需要添加条件你可以做

return Query::with(['department' => function ($query) use ($department) {
           $query->when($department, function ($query) use ($department) {
              $query->whereId($department);
           });
        }, 'category' => function($query) use ($category) {
            $query->when($category, function ($query) use ($category) {
              $query->whereId($category);
           });
        }])->when($activeStatus, function ($query) use ($activeStatus) {
              $activeStatus = (request()->active_status === 'active') ? 1 : 0;
              $query->whereActive($activeStatus);
         })->latest()->paginate($dataPerPage);

或者你可以

return Query::with('department', 'category')
    ->when($department, function($query) use ($department) {
        $query->whereHas('department', function (Builder $query) use ($department) {
            $query->whereId($department);
        });
    })->when($category, function ($query) use ($category) {
        $query->whereHas('category', function (Builder $query) use ($category) {
            $query->whereId($category);
        });
    })->when($activeStatus, function ($query) use ($activeStatus) {
        $activeStatus = (request()->active_status === 'active') ? 1 : 0;
        $query->whereActive($activeStatus);
    })->latest()->paginate($dataPerPage);

相关问题