2014-10-29 29 views
2
的雄辯ORM聯接查詢

目前我有三個表一個是屬性表有以下幾列:我如何編寫使用Laravel

  • ID
  • 描述

第二是標籤表有以下列:

  • ID
  • TAG_NAME
  • tag_status

第三是具有以下各欄樞軸表:

  • ID
  • TAG_ID
  • 在特性模型的PROPERTY_ID

現在我有defi斯內德這樣與數據透視表的關係:

public function tags() 
    { 
     return $this->belongsToMany('Tag'); 
    } 

,並在標籤型號我也像這樣定義與數據透視表的關係:

public function properties() 
    { 
     return $this->belongsToMany('Property'); 
    } 

現在我需要現在是我該怎麼寫下面就使用Laravel的雄辯ORM這三個表的查詢:

$propertyTags=Property::join('property_tag', 'properties.id', '=', 'property_tag.property_id') 
      ->join('tags', 'tags.id', '=', 'property_tag.tag_id') 
      ->where('properties.id','=',$property_id) 
      ->get(['tags.tag_name','tags.id']); 

回答

0

你可以嘗試

$property_obj = Property::find($property_id); 
$property_tags = $property_obj->tags->all(); 

或使用熱切加載

$property_with_tags = Property::with('tags')->where('id','=',$property_id)->get();