【问题标题】:Using HasManyThrough in Laravel在 Laravel 中使用 HasManyThrough
【发布时间】:2019-01-11 06:02:03
【问题描述】:

我有以下结构:

订单 ID 名字

产品 ID 名字

项目 ID order_id product_id 数量

关系如下:

订购

public function items(){
 return $this->hasMany(Item::class)
}

public function products(){
 return $this->hasManyThrough(Product::class, Item::class);
}

物品

public function order(){
 return $this->belongsTo(Order::class);
}

public function product(){
 return $this->belongsTo(Product::class);
}

产品

public function items(){
 return $this->hasMany(Item::class);
}

我希望通过以下方式获取订单的所有产品: $order->items()->products()->get() 使用 hasManyThrough 方法,但我一定做错了,因为它试图在 products 表中查找 item_id。

【问题讨论】:

    标签: laravel-5 eloquent


    【解决方案1】:

    我意识到我不需要很多通过,我只需要使用 items 表作为数据透视表,在 Order 模型上定义关系就像这样:

    public function products(){
     return $this->belongsToMany(Product::class, 'items');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2014-08-14
      • 2017-12-08
      • 2018-10-18
      相关资源
      最近更新 更多