我有两种模式:Order
和Department
,加入了多对多的关系。该关系中的数据透视表包含“状态”字段。因此,一个特定的顺序可能看起来像:Laravel 5.4:高级数据透视表查询问题
- 制造业:完成
- 包装:(不需要/未附)
- 航运:正在进行
在UI我的应用程序我每个部门都有一个选项卡,状态栏有复选框。因此,API需要能够接受具有一个部门和多个可能状态的请求,并返回与给定部门的所选状态匹配的所有订单。
例子查询:/api/orders?dep=manufacturing&statuses=notStarted,inProgress
这需要返回所有订单这是要么或“进步”(在其他任何部门不分身份)“未启动”为制造部门
这里是我写的查询:
$query = Order::with("departments");
$department = Request::get('department');
$statuses = explode(",", Request::get('statuses', ""));
if (!empty($department))
{
$query->whereHas('departments', function ($q) use ($department)
{
$q->where('name', $department);
});
if (count($statuses) > 0)
{
$query->where(function ($q) use ($department, $statuses)
{
foreach ($statuses as $status)
{
$q->orWhereHas('departments', function ($q) use ($department, $status)
{
$q->where('name', $department)->wherePivot('status', $status);
}
}
});
}
}
return $query->paginate(15);
这是引发错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause'
我的关系被定义为如下:
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'order_statuses')->using('App\Models\OrderStatus')->withPivot('status')->withTimestamps();
}
我的关系是使用'withPivot'定义。我将用整个关系定义更新我的原始帖子 – stevendesu