[英]What's the best way to get data with relations?
我需要一些幫助,以找出從以下表結構中獲取數據的最佳方法。
表一:組織ID名稱等
表2:位置ID名稱等
表三: organisaiton_locations該表具有如下關系:
id | organisation_id | location_id
乳清,我嘗試使用hasManyThrough,我得到了正確數量的項目,但它們映射到id而不是location_id 。
class Organisation extends Model
{
public function locations()
{
return $this->hasManyThrough('App\Models\Location', 'App\Models\OrganisationLocation', 'organisation_id', 'id');
}
}
您能否幫助我了解如何獲取集合中與組織相關的所有位置,以便可以在轉換器中使用。
提前致謝。
您不必使用hasManyThough
只使用普通的hasManyThough
,但通過它您嘗試訪問第三級關系,而在您的情況下則不是。
只需將其替換為:
class Organisation extends Model
{
public function locations(){
return $this->hasMany(Location::class,'organisaiton_locations', 'organisation_id', 'location_id')->withTimestamps();
}
}
並且請記住要導入Location類( hasMany
函數中的第一個參數)或將其用作字符串,就像您做的那樣
如果聯結表中沒有時間戳,請從上面代碼的末尾->withTimestamps()
刪除它
我的一位朋友建議將ManyToMany關系與這種表關系一起使用,並且它的工作原理很完美。 如果您遇到這樣的問題,請使用正確的表名(按字母順序)使用ManyToMany,並且按照框架進行操作,不會受到任何干擾。
干杯!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.