2 回答

TA貢獻1802條經(jīng)驗 獲得超4個贊
最后,顯然有幾種方法可以將數(shù)據(jù)從表格中獲取locationsarea_tests
嘗試修補,它的工作原理,
第一個選項
我需要為數(shù)據(jù)透視表創(chuàng)建一個透視模型:
class LocationAreaType extends Pivot{
public function location(){
return $this->belongsTo(Location::class);
}
public function areaType(){
return $this->belongsTo(AreaType::class);
}
public function AreaTests(){
return $this->hasMany(AreaTest::class, 'area_type_location_id');
}
}
我可以使用需要在“位置”表中創(chuàng)建的關(guān)系hasManyThrough
public function areaTests()
{
return $this->hasManyThrough(
AreaTest::class,
LocationAreaType::class,
'location_id',
'area_type_location_id');
}
這樣我就可以很容易地得到這個地區(qū)測試,我的問題是不是確定為外國的。你需要確定這一點,顯然當我擴展樞軸和使用有許多拉拉維爾不會自動識別外鍵本身。$location->areaTestsarea_type_location_id
第二種選擇
訪問它的另一種方法是從關(guān)系表中,我可以在關(guān)系中定義,然后像這樣訪問它:withPivotareaTypes()
$location->areaType[0]->pivot->areaTests
由于拉拉維爾只識別兩個表和的外鍵,我必須包括數(shù)據(jù)透視表才能獲得 AreaTest 表數(shù)據(jù)location_idarea_type_idid
因此,在位置模型中,我必須獲取列
public function areaTypes()
{
// Get the ID of the pivot table to get the poolTests table (connected with ID column)
return $this->belongsToMany(AreaType::class)
->using(AreaTypeLocation::class)
->withPivot('id');
}

TA貢獻1797條經(jīng)驗 獲得超6個贊
無需為數(shù)據(jù)透視表創(chuàng)建新模型。只需在下面代碼的位置模型中聲明:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function area_types()
{
return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');
}
并在區(qū)域類型模型中聲明以下代碼:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function locations()
{
return $this->belongsToMany('App\Location', 'area_type_location', 'area_type_id', 'location_id');
}
例如,每次您需要獲取每個控制器中area_type的位置時,都可以像這樣調(diào)用該函數(shù):$areatype->locations()->get();
不要忘記創(chuàng)建area_type_location表遷移。
如果這個答案解決了您的問題,請單擊??并接受它。
- 2 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報