【问题标题】:Why is my Laravel hasManyThrough not working?为什么我的 Laravel hasManyThrough 不起作用?
【发布时间】: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))
        ];
    }

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以使用以下代码:

    class OrderLine extends Pivot
    {
        use HasFactory;
    
        /**
         * @var bool
         */
        public $timestamps = false;
    
        public function locations(): HasManyThrough
        {
            return $this->hasManyThrough(
                Location::class, //Final model we wish to access
                LocationProduct::class, //The name of the intermediate model
                'product_sku',//Foreign key on location_products table
                'id',//Foreign key on locations table
                'product_sku',//Local key on order_lines table
                'location_id'//Local key on location_products table
            );
        }
    }
    

    如果你有任何问题,请告诉我。

    【讨论】:

    • 我现在要试试这个。
    • 成功了!非常感谢
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2020-11-08
    • 2014-08-31
    • 1970-01-01
    相关资源
    最近更新 更多