【问题标题】:Relationships in has many laravel关系中有很多 laravel
【发布时间】:2016-10-12 02:55:18
【问题描述】:

我有三个表unitsrentersrenter_unitsrender_units 表的字段为 id , unit_id, renter_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
    }
  ]
}

但我也想要renter_unit 字段的relationship 数组。如何实现?

【问题讨论】:

    标签: join laravel-5.2 relationship has-many


    【解决方案1】:

    也许你应该使用Many-To-Many 关系。如果是这样,那么您不需要像 RenterUnit 这样的任何数据透视类,只需要 renter_unit
    然后您的代码将如下所示

    租客.php
    public function units() 
    {
        return $this->belongsToMany('App\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
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-10
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2017-09-03
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多