gpt4 book ai didi

php - SQLSTATE[42S22] : Column not found: 1054 Unknown column one to many(inverse) relation laravel

转载 作者:行者123 更新时间:2023-11-29 05:08:15 25 4
gpt4 key购买 nike

我有两个模型 Tour.phpTourCategory.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');
}

我的数据库表如下:

游览

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

我之前的项目也使用了相同的代码,但没有出现任何错误。还是我遗漏了什么?

最佳答案

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the model is not *_id, you may pass a custom key name as the second argument to the belongsTo method

所以,你需要specify a foreign key :

public function category() 
{
return $this->belongsTo('App\TourCategory', 'category_id');
}

You may also override the foreign and local keys by passing additional arguments to the hasMany method.

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

关于php - SQLSTATE[42S22] : Column not found: 1054 Unknown column one to many(inverse) relation laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44384920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com