2016-11-16 23 views
0

我有兩個包含多對多關係和數據透視表的表格從Laravel查詢構建器獲取數據,並與之保持良好關係

表1: id |名稱| country_id |
表2:國家| id |名稱| Piviot表:country_tour | id | country_id | tour_id |

模型1 Tour.php

public function country() 
{ 
    return $this->belongsToMany('App\Country'); 
} 

模型2 Country.php

public function tours() 
{ 
    return $this->belongsToMany('App\Tour'); 
} 

如何可以獲取與查詢生成器數據。我想這

$featured = DB::table('tours')->where('country', 'Croatia')->get(); 

和我收到提示

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country' in 'where clause' (SQL: select * from `tours` where `country` = Croatia) 
+0

這是什麼意思分類在這裏..你最終想要什麼? –

+0

它看起來像是在查詢錯誤的列,'tour'表沒有任何'category'列。爲什麼在巡迴表中有'country_id'列,這裏沒有意義。 –

+0

是的,的確,我在查詢中犯了錯誤。現在我已經做了更正,但仍然出現錯誤。我如何從數據透視表中獲取數據?常用模型是否有助於解決數據問題? –

回答

0

我看這不是一個多到多的關係。多對多將是hasAndBelongsToMany而不是belongsToMany。但是你的查詢的問題是不同的。您的tours表格沒有現有的category列。順便說一下,您可以使用\App\Tour::where()而不是DB::table('tours')->where()。這就是模型類的用途。