【问题标题】:How to filter on pivot fields in laravel如何过滤laravel中的数据透视字段
【发布时间】:2016-01-10 13:00:08
【问题描述】:

我有 3 个表格,usersordersstatuses。数据透视表 order_status 有额外的列:user_idcreated_at(用于获取哪个用户以及何时设置该状态)。 Order模型有方法:

// get latest status for order, and tie user (user_id in pivot table)    
public function latestStatus(){
        return $this->belongsToMany('Status')
                ->select(array('*','User.name'))
                ->orderBy('order_status.created_at','desc')
                ->join('users','order_status.user_id','=','users.id')
                ->withTimestamps();
                ->limit(1,0);
        }

所以如果我打电话:

$orders = Orders::with('latestStatus')->get();

我可以收到最新状态的订单。没关系。

我需要对订单属性和最新状态进行一些过滤,例如:(orders 表有 locationbuyer 列>) - 如何拉取所有订单:

order.location_id = in ("ny", "nm")
order.buyer_id = in ("1", "3")
order_status.user_id = in ("1", "5")
order_status.created_at = between (2015-10-04, 2015-10-06)
order_status.status_id = in ("2", "8", "9")

在 Orders 上调用“where”只是解决了位置和买家部分问题...

$orders = Orders::whereIn('location_id',["ny", "nm"])
         ->whereIn('buyer_id',["1","3"])
         ->with('latestStatus')
         ->get();

所以问题是如何过滤数据透视字段(查找在特定日期之间创建的具有特定状态的订单)?

tnx 是的

【问题讨论】:

    标签: mysql eloquent laravel-5.1


    【解决方案1】:

    好的,我是这样做的:

    $orders = Order::with('lateststatus')
        ->whereHas('lateststatus', function ($q) use ($dateTo, $dateFrom, $statuses) {
                                    $q->where('order_status.created_at','>=',$dateFrom);
                                    $q->where('order_status.created_at','<',$dateTo);
                                    $q->whereIn('order_status.status_id',$statusi); 
                                }
                );
    $orders = $orders->whereIn('location_id',$locations); }
    $orders = $orders->whereIn('user_id',$users); }
    $orders = $orders->->get();
    

    PS:我改变了数据库结构,所以现在我将 user_id 保存在订单表中。

    【讨论】:

      猜你喜欢
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 2018-12-31
      • 2017-10-17
      • 2019-09-17
      • 1970-01-01
      相关资源
      最近更新 更多