Laravel很多人都不工作

时间:2017-09-06 11:59:26

标签: php mysql laravel

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

Posts
Tags

我有一个名为post_tag的数据透视表。

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

@foreach($posts as $post)

    {{ dd($post->tags)  }}

@endforeach

我收到以下错误:

  

SQLSTATE [42S22]:找不到列:1054未知列'tags.post_id'   在'where子句'中(SQL:select * from tags where tagspost_id =   1和tagspost_id不为空)(查看:   C:\瓦帕\ WWW \ laravel \资源\视图\帖\ 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);
    }

}

关于这里发生的任何想法?我在数据透视表中有数据,但似乎关系不正常。

3 个答案:

答案 0 :(得分:2)

你应该对两个关系使用belongsToMany

class Post extends Model
{
   ....

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

}

答案 1 :(得分:1)

您应该在帖子模型中使用belongsToMany,请查看documentation

class Post extends Model
{
 ....

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

}

答案 2 :(得分:1)

必须在模型中定义

数据透视表的名称和外键

类Post扩展Model {    ....

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

}

类标签扩展了Model {    ....

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

}

相关问题