【发布时间】:2019-06-18 23:03:20
【问题描述】:
我的问题是我试图在帖子和流派之间建立多对多的关系。这是我到目前为止所做的。
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 |
+----+----------------+
genre_post 表
+----+---------+----------+
| 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 未知列 'post.genre_id' 在 'where 子句' (SQL: select * from
postwherepost.genre_id
我了解 laravel 正试图从 post 表中获取 genre_id 列,该表不存在,因为它是多对多关系,这意味着一篇文章可以包含一种以上的流派,一种流派可以包含多个发帖。
知道如何解决这个问题吗?
【问题讨论】:
-
hasMany是一对多关系,使用belongsToMany。