mysql - 如何在 laravel 中过滤数据透视字段

标签 mysql eloquent laravel-5.1

我有 3 个表,用户订单状态。数据透视表 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();

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

我需要对订单属性和最新状态进行一些过滤,例如:(表订单有列位置买家) - 如何提取所有订单:

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

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

发送邮件 对

最佳答案

好的,这是我的做法:

$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 保留在订单表中。

关于mysql - 如何在 laravel 中过滤数据透视字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33091451/

相关文章:

javascript - laravel Elixir 映射类似文件

php - 拉维尔 5.1 : Relationships with SQLite rowid?

mysql - EntityFramework异常: How can i see the real query

mysql - 你如何在 (?) 调用中执行 SQL 查找?

mysql - Laravel 查询构建器表连接

mysql - Eloquent 不会更新 MySQL 中的所有记录

php - 在 laravel5.1 中使用 FileSystem 上传文件?

php - 当数组为空时进行 while 循环?

php - 从 MySQL 读取更快还是从文件读取更快?

mysql - 违反完整性约束 : 1052 Column and in where clause is ambiguous