我有两个模型Tour.php
和TourCategory.php
:
Tour.php
protected $table = `tours`;
public function category()
{
return $this->belongsTo('App\TourCategory');
}
TourCategory.php
protected $table = 'tcategories';
public function tours()
{
return $this->hasMany('App\Tour');
}
我的数据库表格如下:
tours
表
id|title|category_id|content|
tcatgegories
表
id|name
我希望通过以下代码显示属于某个类别的所有游览:
@foreach ($category->tours as $tour)
<tr>
<th>{{ $tour->id}}</th>
<td>{{ $tour->title}}</td>
<td>
<span class="label label-default">{{$category->name}}</span>
</td>
</tr>
@endforeach
使用上面的代码我得到错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tours.tour_category_id' in
'where clause' (SQL: select * from `tours` where `tours`.`tour_category_id` = 1 and
`tours`.`tour_category_id` is not null) (View: F:\multiauth_tutorial-master\resources\
views\admin\categories\show.blade.php
我以前的项目也使用了相同的代码,但没有任何错误。或者我错过了什么?
答案 0 :(得分:2)
Eloquent通过检查关系方法的名称并使用
_id
为方法名称添加后缀来确定默认外键名称。但是,如果模型上的外键不是*_id
,则可以将自定义键名作为第二个参数传递给belongsTo
方法
所以,你需要specify a foreign key:
public function category()
{
return $this->belongsTo('App\TourCategory', 'category_id');
}
您还可以通过将其他参数传递给
hasMany
方法来覆盖外键和本地键。
public function tours()
{
return $this->hasMany('App\Tour', 'category_id');
}
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many
或在旅行表中使用tour_category_id
代替category_id
。
答案 1 :(得分:1)
在Tour.php中
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function tours()
{
return $this->hasMany(Tour::class, 'category_id');
}
在TourCategory.php中
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo(TourCategory::class, 'category_id');
}
答案 2 :(得分:0)
在tour_category_id
表中找不到此列tours
,将您的sql查询更改为
select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null