在搜索表单之前修改的查询代码然后我用下面的查询,这完美地工作。
...
$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 . '%');
...
但现在我作如下修改表结构通过关系查询dynimically字段名显示。
工作表
+----------------------------------------------------+
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 | ...
+-------------------------------+
作业类型表
+------------------+
ID | name | ...
+------------------+
1 | test1 |...
+------------------+
2 | test2 | ...
+------------------+
它也包括如下面工作模型的简单关系。这些东西定义为varchar类型为字符串。但工作模型中定义的不仅仅是这些模型在工作表中的customer_id,PROJECT_ID和jobType_id 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和工作类型,那么如何让查询关系查询链?由于工作表只包括这些ID。
<?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 . '%');
});
});