Php SQLSTATE[42S22]:未找到列:1054未知列一对多(反向)关系laravel
我有两个模型Php SQLSTATE[42S22]:未找到列:1054未知列一对多(反向)关系laravel,php,mysql,laravel,blade,laravel-5.4,Php,Mysql,Laravel,Blade,Laravel 5.4,我有两个模型Tour.php和TourCategory.php: Tour.php protected $table = `tours`; public function category() { return $this->belongsTo('App\TourCategory'); } protected $table = 'tcategories'; public function tours() { return $this->hasMany('App
Tour.php
和TourCategory.php
:
Tour.php
protected $table = `tours`;
public function category()
{
return $this->belongsTo('App\TourCategory');
}
protected $table = 'tcategories';
public function tours()
{
return $this->hasMany('App\Tour');
}
TourCategory.php
protected $table = `tours`;
public function category()
{
return $this->belongsTo('App\TourCategory');
}
protected $table = 'tcategories';
public function tours()
{
return $this->hasMany('App\Tour');
}
我的数据库表如下:
tours
表格
id |标题|类别| id |内容|
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
我以前的项目也使用了相同的代码,但没有任何错误。还是我遗漏了什么?在您的
tours
表中找不到此列tours\u category\u id
lis,请将sql查询更改为
select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null
此列
tours\u category\u id
lis未在tours
表中找到,请将sql查询更改为
select * from `tours` where `tours`.`category_id` = 1 and `tours`.`category_id` is not null
Eloquent通过检查关系方法的名称并在方法名称后面加上\u id
来确定默认外键名称。但是,如果模型上的外键不是*\u id
,则可以将自定义键名作为第二个参数传递给belongsTo
方法
因此,您需要:
您还可以通过向hasMany
方法传递附加参数来覆盖外键和本地键
或者使用tour\u category\u id
而不是tours表中的category\u id
Eloquent通过检查关系方法的名称并在方法名称后面加上\u id
来确定默认外键名称。但是,如果模型上的外键不是*\u id
,则可以将自定义键名作为第二个参数传递给belongsTo
方法
因此,您需要:
您还可以通过向hasMany
方法传递附加参数来覆盖外键和本地键
或者在tours表中使用tour\u category\u id
而不是category\u id
。在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');
}
在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');
}
我知道,但我过去在
旅游
中有过类别id
字段。应用程序正在查找不存在的列。我知道,但我过去在tours
中的category\u id
字段中有过。应用程序正在查找不存在的列。添加了category\u id
作为外键,错误仍然是一样的。@TanjaForsberg您最初的问题是关于一对多的反向关系(即belongsTo()
)。如果使用的是tours()
关系,则还需要向hasMany()
关系添加自定义外键名称。您可以在更新的答案中看到一个示例。感谢您的宝贵指导。我会永远记住你的建议。添加了category\u id
作为外键,错误仍然是一样的。@TanjaForsberg你原来的问题是关于一对多的反向关系(即belongsTo()
)。如果使用的是tours()
关系,则还需要向hasMany()
关系添加自定义外键名称。您可以在更新的答案中看到一个示例。感谢您的宝贵指导。我会永远记住你的建议。