我有兩個表與數據透視表與數據透視表Laravel查詢生成器
表tours
id | name | country_id | featured
表countries
id | name
透視表country_tour
id | country_id | tour_id
我想找到有旅行團表featured
列設置爲1和country_tour
表country_id
設置爲1
我有兩個表與數據透視表與數據透視表Laravel查詢生成器
tours
id | name | country_id | featured
countries
id | name
country_tour
id | country_id | tour_id
我想找到有旅行團表featured
列設置爲1和country_tour
表country_id
設置爲1
更新遊:
你可以這樣做像這樣利用Laravel的查詢生成器方法 - whereHas()
:
你的模型應該像這樣(多對多關係):
旅遊型號:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tour extends Model
{
public function countries() {
return $this->belongsToMany('App\Country');
}
}
和國家示範
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public function tours() {
return $this->belongsToMany('App\Tour');
}
}
,現在你可以通過使用下面的查詢獲取所需的結果:
Tour::where('featured', 1)
->whereHas('countries', function($q) {
$q->where('id', 1);
})
->get();
這將讓你的集旅遊與並具有country with id = 1
的。
希望這會有所幫助!
感謝隊友的快速回復。該代碼運行後,沒有錯誤後,我改變ID爲country_id功能,因爲它是拋出錯誤少tweks。但是代碼沒有從db中獲取任何數據。 –
Wair對我來說,因爲我很快更新我的答案... –
,我也改變了國家作爲國家我的方法的名稱是國家。 –
你什麼嘗試提供。 –
你的關係看起來像這樣 - 「國家有很多旅遊團」和「旅遊有很多國家」? –