Laravel 多对多不工作

Laravel Many to Many not working

我有一个基本的多对多关系:

Posts
Tags

我有一个名为 post_tag 的枢轴 table。

我正在尝试 return 我的视图文件中所有给定的帖子标签:

@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 where tags.post_id = 1 and tags.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);
    }

}

关于这里发生的事情有什么想法吗?我在数据透视表 table 中有数据,但似乎关系不正常。

你应该对这两个关系使用 belongsToMany

class Post extends Model
{
   ....

    public function tags() {
        return $this->belongsToMany(\App\Models\Tag::class);
    }

}

您应该在 Post 模型中使用 belongsToMany,检查 documentation

class Post extends Model
{
 ....

  public function tags() {
      return $this->belongsToMany(\App\Models\Tag::class);
  }

}

数据透视表的名称和外键必须在模型中定义

class Post 扩展模型 { ....

public function tags() {
    return $this->belongsToMany(\App\Models\Tag::class,'post_tag','tag_id',post_id);
}

}

class 标签扩展模型 { ....

public function Posts() {
    return $this->belongsToMany(\App\Models\Tag::class,'post_tag','post_id',tag_id);
}

}

我遇到过这个问题,现在我已经解决了!

Post型号:

public function tags() {
    return $this->belongsToMany(\App\Models\Tag::class,'post_tag','post_id', 'tag_id');
}

标签模型:

public function posts() {
    return $this->belongsToMany(\App\Models\Tag::class,'post_tag','post_id', 'tag_id');
}