【发布时间】:2021-09-16 10:18:03
【问题描述】:
我有一个这样的表结构:
order_lines
- order_id
- product_sku
- 价格
location_products
- product_sku
- location_id
地点
- 身份证
- 姓名
在我的OrderLine 模型中,我有一个hasManyThrough 来通过productLocations 表获取位置。其结构如下:
class OrderLine extends Pivot
{
use HasFactory;
/**
* @var bool
*/
public $timestamps = false;
public function locations(): HasManyThrough
{
return $this->hasManyThrough(
Location::class,
LocationProduct::class,
'location_id',
'id',
'product_sku',
'product_sku'
);
}
}
注意事项:
- location_products 和 order_lines 没有名为 id 的列。 从理论上讲,这个解决方案应该有效,但实际上并没有。
- 一个订单行可以有多个 location_products
- 一个 location_products 可以有多个位置
一些示例数据:
order_lines
- 2 (order_id)
- 80176 (product_sku)
- 14.99 (price)
location_products
- 80176 (product_sku)
- 1433 (location_id)
locations
- 1433 (id)
- Location 1433 (name)
我做错了什么?这样做时我总是得到一个空数组。
我是这样称呼的:
$order_lines = OrderLine::query()->where("order_id", "=", $order_id)->with("product")->get();
return OrderLineResource::collection($order_lines);
OrderLineResource:
public function toArray($request): array
{
return [
'orderId' => $this->order_id,
'productId' => $this->product->id,
'productName' => $this->product->name,
'productSku' => $this->product->sku,
'price' => number_format($this->price, 2, '.', ''),
'discount' => $this->discount,
'quantity' => $this->quantity,
'tax' => $this->tax,
'createdAt' => $this->created_at,
'updatedAt' => $this->updated_at,
'locations' => LocationResource::collection($this->whenLoaded($this->locations))
];
}
【问题讨论】: