亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

拉拉維爾表與數據透視表的關系

拉拉維爾表與數據透視表的關系

PHP
繁星點點滴滴 2022-09-25 20:31:32
我對如何使用連接到數據透視表的表在laravel中獲取模型設置感到困惑。這是問題所在假設我有Locations    id    namearea_types    id    namearea_type_location (Pivot table)    id    location_id    area_type_idarea_test    id    area_type_location_id    clean    headCount表之間的關系是不同的區域類型屬于不同的位置。即:海灘,25米游泳池,兒童游泳池,燒烤等area_test連接到數據透視表,因為測試必須從存在的區域生成,在這種情況下,它是在不同位置下注冊的區域。因此,它必須每天進行測試,測量等。我了解area_types和位置之間的結構,但是我無法克服如何構建我的area_test模型?如何從位置表中獲取數據 >我的測試在哪里?我應該為數據透視表創建模型嗎?這在拉拉維爾是一個好習慣嗎?有沒有人有相同的用例?我讀到關于雄辯有很多通過關系,但我明白它沒有提到通過數據透視表。我不太明白我的用例是否相同。謝謝
查看完整描述

2 回答

?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

最后,顯然有幾種方法可以將數據從表格中獲取locationsarea_tests


嘗試修補,它的工作原理,


第一個選項

我需要為數據透視表創建一個透視模型:


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');

}

}


我可以使用需要在“位置”表中創建的關系hasManyThrough


public function areaTests()

{

    return $this->hasManyThrough(

        AreaTest::class,

        LocationAreaType::class,

        'location_id',

        'area_type_location_id');

}

這樣我就可以很容易地得到這個地區測試,我的問題是不是確定為外國的。你需要確定這一點,顯然當我擴展樞軸和使用有許多拉拉維爾不會自動識別外鍵本身。$location->areaTestsarea_type_location_id


第二種選擇

訪問它的另一種方法是從關系表中,我可以在關系中定義,然后像這樣訪問它:withPivotareaTypes()


$location->areaType[0]->pivot->areaTests


由于拉拉維爾只識別兩個表和的外鍵,我必須包括數據透視表才能獲得 AreaTest 表數據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');

}


查看完整回答
反對 回復 2022-09-25
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

無需為數據透視表創建新模型。只需在下面代碼的位置模型中聲明:


  /**

   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany

   */

  public function area_types()

  {

        return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');


  }

并在區域類型模型中聲明以下代碼:


  /**

   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany

   */

  public function locations()

  {

        return $this->belongsToMany('App\Location', 'area_type_location', 'area_type_id', 'location_id');


  }

例如,每次您需要獲取每個控制器中area_type的位置時,都可以像這樣調用該函數:$areatype->locations()->get();


不要忘記創建area_type_location表遷移。


如果這個答案解決了您的問題,請單擊??并接受它。


查看完整回答
反對 回復 2022-09-25
  • 2 回答
  • 0 關注
  • 137 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號