在laravel 5.4中有很多对很多人

时间:2017-02-13 20:36:43

标签: laravel-5 eloquent laravel-eloquent

我有三种模式:

Product
Inventory
Order

他们之间的关系如:

订单与Inventory和$ nventory-> belongsTo(' product')有很多关系;

/** Product Model **/
class Product extend Model 
{

    public function inventories()
    {
        return $this->hasMany('App\Inventory');
    }
}

/** Inventory Model **/
class Inventory extend Model 
{

    public function products()
    {
        return $this->belongsTo('App\Product');
    }
}

/** Order Model **/
class Order extend Model {

    public function inventories()
    {
        return $this->belongsToMany('App\Inventory','order_items');
    }


    //how do I get this?
    public function products()
    {

    }
}

由于hasManyThrough数据透视表,order_items无效。我怎样才能获得订单的产品?

1 个答案:

答案 0 :(得分:0)

在这种情况下没有本机关系。

我创建了HasManyThrough关系,并支持BelongsToManyRepository on GitHub

安装后,您可以像这样使用它:

class Order extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function products() {
        return $this->hasManyDeep(Product::class,
            ['order_items', Inventory::class],
            [null, null, 'id'],
            [null, null, 'product_id']
        );
    }
}