Laravel雄辩的模型关系查询

时间:2019-02-04 00:37:12

标签: laravel eloquent laravel-query-builder

在修改搜索表单中的查询代码之前,我在下面的查询中使用了它,效果很好。

...
$query = Job::where('is_trash', 0);
$query = $query->where('created_at', '>=', Carbon::parse($rFrom)->startOfDay())
        ->where('created_at', '<=', Carbon::parse($rTo)->endOfDay())
        ->where('customer_name', 'like', '%' . $rName . '%')
        ->where('project_name', 'like', '%' . $rProject . '%')
        ->where('job_type', 'like', '%' . $rType . '%');
...

但是现在我将下面的表结构修改为动态显示字段名称 通过使用关系查询。

工作表

  +----------------------------------------------------+
     ID | customer_id | job_project_id | job_type_id | ...                                         
  +----------------------------------------------------+
     1  | 1           | 1             | 1       | ...
  +----------------------------------------------------+
     2  | 2           | 7             | 2       | ...
  +----------------------------------------------------+

JobProject表

  +-------------------------------+
     ID | customer_id | name | ...                                         
  +-------------------------------+
     1  | 1           | 1    |...
  +-------------------------------+
     2  | 2           | 7    | ...
  +-------------------------------+

JobType表

  +------------------+
     ID | name  | ...                                         
  +------------------+
     1  | test1 |...
  +------------------+
     2  | test2 | ...
  +------------------+

在Job模型中还包括以下简单关系。这些东西将varchar类型定义为字符串。但是Job模型仅将这些模型的ID定义为job表中的customer_id,project_id和jobType_id。

...

public function user()
{
    return $this->hasOne(User::class);
}

public function customer()
{
    return $this->hasOne(Customer::class);
}

public function jobProject()
{
    return $this->hasOne(JobProject::class);
}

public function jobType()
{
    return $this->hasOne(JobType::class);
}
...

主要问题是,如果搜索输入是customer_name,project_name和job_type,那么如何建立查询关系查询链?因为Job表仅包含这些ID。

1 个答案:

答案 0 :(得分:0)

<?php 

// Build primitive query
$jobQuery = Job::where('is_trash', 0);

// Use when conditional to check if you need to filter something
$jobQuery->when($from && $to, function($q) use($request) {
        $q->where('created_at', '>=', Carbon::parse($from)->startOfDay())
            ->where('created_at', '<=', Carbon::parse($to)->endOfDay());
    });
// Use whereHas to add a where clause in relations
$jobQuery->when($customerName, function($q) use($request) {
    $q->whereHas('customer', function ($subq) {
        $subq->where('name', 'like', '%' . $customerName . '%');
    });
});


$jobQuery->when($projectName, function($q) use($request) {
    $q->whereHas('jobproject', function ($subq) {
        $subq->where('name', 'like', '%' . $projectName . '%');
    });
});

$jobQuery->when($jobType, function($q) use($request) {
    $q->whereHas('jobtype', function ($subq) {
        $subq->where('name', 'like', '%' . $jobType . '%');
    });
});