我有两个具有多对多关系的表和透视表
表1:tours | id | name | country | U id |
表2:countries | id | name | Piviot表:country | U tours | id | country | U id | tours ||
模式1之旅。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)
在我看来,这不是一种多对多的关系。多对多将是hasandbelongtomany
而不是belongtomany
。但您的查询的问题不同。您的tours
表没有现有的category
列。顺便说一下,您可以使用\App\Tour::where()
而不是DB::table('tours')-
要利用eloquent的模型关系,您需要使用模型本身,而不是数据库查询:
$croatia = App\Country::whereName('Croatia')->first();
$toursInCroatia = $croatia->Tours;