关系中有许多laravel

时间:2016-06-11 04:59:51

标签: join laravel-5.2 relationship has-many

我有三张表unitsrentersrenter_unitsrender_units表的字段为idunit_idrenter_id

我的Render型号

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

在我的RentersController

$renters = Renter::with('renter_unit')->get();

所以$renders数组显示

Collection {#212 ▼
  #items: array:1 [▼
    0 => Renter {#206 ▼
      #fillable: array:3 [▶]
      #table: "renters"
      #guarded: array:1 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:7 [▶]
      #original: array:7 [▶]
      #relations: array:1 [▼
        "renter_unit" => Collection {#210 ▼
          #items: array:2 [▼
            0 => RenterUnit {#213 ▼
              #fillable: array:2 [▶]
              #table: "renter_units"
              #guarded: array:1 [▶]
              #connection: null
              #primaryKey: "id"
              #perPage: 15
              +incrementing: true
              +timestamps: true
              #attributes: array:5 [▼
                "id" => 1
                "unit_id" => 1
                "renter_id" => 1
                "created_at" => "2016-06-11 02:40:44"
                "updated_at" => "2016-06-11 02:40:44"
              ]
              #original: array:5 [▶]
              #relations: []
              #hidden: []
              #visible: []
              #appends: []
              #dates: []
              #dateFormat: null
              #casts: []
              #touches: []
              #observables: []
              #with: []
              #morphClass: null
              +exists: true
              +wasRecentlyCreated: false
            }
            1 => RenterUnit {#214 ▶}
          ]
        }
      ]
      #hidden: []
      #visible: []
      #appends: []
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
}

但我也想要relationship字段用于renter_unit字段。如何实现?

1 个答案:

答案 0 :(得分:0)

可能你应该使用Many-To-Many关系。如果是这样,那么您不需要任何像RenterUnit这样的支点类,只需要renter_unit
然后你的代码将如下所示

Renter.php
public function units() 
{
    return $this->belongsToMany('App\Unit');
}
Unit.php
public function renters() 
{
    return $this->belongsToMany('App\Renter');
}

在RentersController中,您可以访问与每个租借者实例相关的单位

$renters = Renter::with('units')->get();
foreach($renters as $renter) {
     $units = $renter->units; //here they are, it's a collection
}