我有一个基本的多对多关系:
Posts
Tags
我有一个名为 post_tag
的数据透视表。
我正在尝试在我的 View 文件中返回所有给定的帖子标签:
@foreach($posts as $post)
{{ dd($post->tags) }}
@endforeach
我收到以下错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags.post_id' in 'where clause' (SQL: select * from
tags
wheretags
.post_id
= 1 andtags
.post_id
is not null) (View: C:\wamp\www\laravel\resources\views\posts\index.blade.php)
这是我的模型:
class Post extends Model
{
....
public function tags() {
return $this->hasMany(\App\Models\Tag::class);
}
}
class Tag extends Model
{
....
public function posts() {
return $this->belongsToMany(\App\Models\Post::class);
}
}
关于这里发生的事情有什么想法吗?我在数据透视表中有数据,但关系似乎无法正常工作。
最佳答案
你应该对这两个关系使用 belongsToMany
class Post extends Model
{
....
public function tags() {
return $this->belongsToMany(\App\Models\Tag::class);
}
}
关于php - Laravel 多对多不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46074660/