如何从多个关系中获取数据

时间:2019-10-01 11:33:26

标签: laravel eloquent

我正在尝试使用口才查询在3个表之间获取数据。

Table 1
  - user (hasMany relationship with orders)

Table 2
  - products (belogsToMany relationship with orders)

Table 3
  - orders (belongsToMany relationship with products)

Pivot table
  - order_details (Pivot table between products and orders)

我尝试着急于加载关系。

User.php

class User extends Model 
{
      public function orders()
        {
           return $this->hasMany('Model\Orders');
        }
}

Product.php

class Product extends Model 
{
    public function orders()
    {
       return $this->belongsToMany('Model\Order', 'order_details', 'product_id', 'order_id')->withPivot('quantity', 'price')->withTimestamps();
    }
}

Orders.php

class Orders extends Model
{
      public function user()
    {
       return $this->belongsTo('Model\User');
    }

    public function products()
    {
       return $this->belongsToMany('Model\Product', 'order__details', 'order_id', 'product_id')->withPivot('quantity', 'price')->withTimestamps();
    }
}

急于加载会返回整个数据集,我正尝试为特定用户进行检索。

0 个答案:

没有答案