我有一个订单表,其中包含存储在数据透视表中的行项目。
成功处理所有订单项后,订单将被标记为“已处理”并需要显示在页面上。
因此,我想获取所有已标记为“已处理”的订单以及各自订单中包含的订单项。
我的查询如下所示:
$orders = DB::table('order_product')
->join('products', 'order_product.product_id', '=', 'products.product_id')
->join('orders', 'order_product.order_id', '=', 'orders.order_id')
->join('customers', 'orders.customer_id', '=', 'customers.customer_id')
->where('order_product.variation_status', '=', 'dispatch')
->where('orders.store', '!=', 'null')
->groupBy('order_product.order_id')
->get();
return response()->json($orders);
我的想法是获取所有已处理的数据透视表项目,然后按order_id对结果进行分组,但遗憾的是这不起作用。
遗憾的是,variation 属性仅包含数据透视表中的一个行项目,而不是两个。
有人可以帮我解决我可能做错了什么吗?
更新
这是我的模型 订单.php
/**
* The products that belong to the Order.
*/
public function products()
{
return $this->belongsToMany('App\Product','order_product','order_id','product_id')
->withPivot(['qty', 'variation', 'variation_status'])
->withTimeStamps();
}
/**
* The customer that belongs to the Order.
*/
public function customer()
{
return $this->belongsTo('App\Customer', 'customer_id');
}
产品.php
/**
* The orders that belong to the product.
*/
public function orders()
{
return $this->belongsToMany('App\Order')
->withPivot(['qty', 'variation_status'])
->withTimeStamps();
}
最佳答案
我不能立即保证这是正确的,因为我通常不使用 ->withPivot
并且还没有运行测试环境,所以这是我的想法片刻。但这可能会让您了解如何处理这个用例。
让我们从订单作为基础开始
Order::get();
现在让我们扩展此功能以检索包含客户和产品的订单
Order::with('customer', 'products')->get();
我们现在要做的是解决上述 Eloquent 查询中的 where 条件:
->where('order_product.variation_status', '=', 'dispatch')
->where('orders.store', '!=', 'null')
您可以执行以下操作:
Order::with(['products' => function($query){
$query->where('variation_status', 'dispatch');
}, 'customer'])
->where('store','!=','NULL')
->get();
关于php - Laravel Eloquent 获取所有行及其各自的数据透视表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47076733/