【问题标题】:Laravel ORM many to many relationship acts like one to manyLaravel ORM 多对多关系就像一对多
【发布时间】: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 post where post.genre_id

我了解 laravel 正试图从 post 表中获取 genre_id 列,该表不存在,因为它是多对多关系,这意味着一篇文章可以包含一种以上的流派,一种流派可以包含多个发帖。

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

【问题讨论】:

  • hasMany 是一对多关系,使用belongsToMany

标签: php laravel orm


【解决方案1】:

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

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2017-12-24
    • 2018-03-16
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多