dongxuan1314 2017-02-15 03:31
浏览 121
已采纳

Laravel 5.4:高级数据透视表查询问题

I have two models: Order and Department, joined by a many-to-many relationship. The pivot table on this relationship contains a "status" field. So a particular order may look something like:

  • Manufacturing: completed
  • Packaging: (not needed / not attached)
  • Shipping: in progress

In the UI for my app I have a tab for each department and checkboxes for statuses. So the API needs to be able to take a request with one department and multiple possible statuses and return all orders which match one of the selected statuses for the given department.

Example query: /api/orders?dep=manufacturing&statuses=notStarted,inProgress

This needs to return all orders which are either "not started" or "in progress" for the manufacturing department (regardless of status in any other department)

Here is the query I wrote:

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

This is throwing the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause'

My relationship is defined as follows:

public function departments()
{
    return $this->belongsToMany('App\Models\Department', 'order_statuses')->using('App\Models\OrderStatus')->withPivot('status')->withTimestamps();
}
  • 写回答

2条回答 默认 最新

  • dongranding3909 2017-04-26 13:27
    关注

    I ultimately came up with the following solution to this:

    if (!empty($departments)
    {
        if (count($statuses) > 0)
        {
            $query->whereHas('departments', function ($q) use ($department, $statuses)
            {
                $q->where('name', $department)->whereIn('order_statuses.status', $statuses);
            }
        } else {
            $query->whereHas('departments', function ($q) use ($department)
            {
                $q->where('name', $department);
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起