Php Laravel ORM多对多关系的行为就像一对多

Php Laravel ORM多对多关系的行为就像一对多,php,laravel,orm,Php,Laravel,Orm,我的问题是我试图在帖子和体裁之间建立一种多对多的关系。以下是我迄今为止所做的工作 class Post extends Model { public function genres() { return $this->belongsToMany('App\Genre'); } } class Genre extends Model { public function posts() { return $this-

我的问题是我试图在帖子和体裁之间建立一种多对多的关系。以下是我迄今为止所做的工作

class Post extends Model
{

    public function genres()
    {
        return $this->belongsToMany('App\Genre');
    }

}

class Genre extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

}
类型表

+----+--------+
| id |  name  |
+----+--------+
|  1 | News   |
|  2 | Sports |
+----+--------+
邮政桌

+----+----------------+
| id |     title      |
+----+----------------+
|  1 | Political News |
|  2 | Sport Update   |
+----+----------------+
+----+---------+----------+
| id | post_id | genre_id |
+----+---------+----------+
|  1 |       1 |        1 |
|  2 |       1 |        2 |
|  3 |       2 |        2 |
+----+---------+----------+
邮政表格

+----+----------------+
| id |     title      |
+----+----------------+
|  1 | Political News |
|  2 | Sport Update   |
+----+----------------+
+----+---------+----------+
| id | post_id | genre_id |
+----+---------+----------+
|  1 |       1 |        1 |
|  2 |       1 |        2 |
|  3 |       2 |        2 |
+----+---------+----------+
当我试图访问一篇文章的类型列表时,一切都很好

Post::where('slug', '=', $id)->with("genres")->first(); // no problem
但当我尝试相反的方法时,它不起作用

$posts = Genre::where( "slug", "=", $id )->with("posts")->first();
我得到以下错误

未找到列:1054“where”中的未知列“post.genre_id” 子句“(SQL:select*from
post
where
post
genre\u id

我知道laravel试图从
post
表中访问
genre\u id
列,该列不存在,因为它是一个多对多关系,这意味着一篇文章可以包含多个流派,而一个流派可以包含多个帖子


知道如何解决这个问题吗?

这是意料之中的,因为
本身就有一对多的关系。请改用
belongTomany

class Genre extends Model
{
    public function posts()
    {
        return $this->belongsToMany('App\Post');
    }

}

hasMany
是一对多关系,使用
belongtomany