与链接表的2个表之间的关系



我有此表:

topics
-------
id    |   title
------+----------
1     |   Sport
2     |   Social
posts_topics
------------
id    |   post_id    |   topic_id
------+--------------+------------
1     |    1         |     1
2     |    1         |     2
posts
------
id   |   title
-----+----------
1    |   A Test Post

我将主题存储在topics表中,并使用posts_topics在我的posts表和topics

之间链接

现在我想在选择帖子时选择 title主题,

在Stackoverflow和Google中进行了一些搜索后,我已经编写了此模型:

posts.php

public function post_topics()
    {
        return $this->hasMany('AppPostTopics');
    }

posttopics.php

public function topics()
    {
        return $this->hasManyThrough('AppPosts', 'AppTopics', 'id', 'topic_id');
    }

topics.php

protected $table = 'topics';

,在我的控制器中,我试图获取:

$post = Posts::with('post_topics')->find($post_id);
dd($post);

现在,此代码将起作用,但无法返回主题的标题。

将代码更改为posts.php中的许多关系:

public function post_topics()
{
    return $this->belongsToMany('AppTopics', 'posts_topics', 'post_id', 'topic_id');
}

,然后称其为:

$post = Posts::with('post_topics')->find($post_id);

尝试一下,检查它是否适合您。

最新更新