Laravel 具有链接表的两个表之间的关系

Laravel 具有链接表的两个表之间的关系,laravel,orm,relational-database,laravel-5.4,Laravel,Orm,Relational Database,Laravel 5.4,我有以下表格: topics ------- id | title ------+---------- 1 | Sport 2 | Social posts_topics ------------ id | post_id | topic_id ------+--------------+------------ 1 | 1 | 1 2 | 1 | 2 posts

我有以下表格:

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\u topics
链接我的
posts
表和
topics

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

在StackOverflow和Google中搜索之后,我编写了以下模型:

Posts.php

public function post_topics()
    {
        return $this->hasMany('App\PostTopics');
    }
public function topics()
    {
        return $this->hasManyThrough('App\Posts', 'App\Topics', 'id', 'topic_id');

    }
protected $table = 'topics';
PostTopics.php

public function post_topics()
    {
        return $this->hasMany('App\PostTopics');
    }
public function topics()
    {
        return $this->hasManyThrough('App\Posts', 'App\Topics', 'id', 'topic_id');

    }
protected $table = 'topics';
Topics.php

public function post_topics()
    {
        return $this->hasMany('App\PostTopics');
    }
public function topics()
    {
        return $this->hasManyThrough('App\Posts', 'App\Topics', 'id', 'topic_id');

    }
protected $table = 'topics';
在我的控制器中,我试图获取:

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

现在,此代码可以工作,但无法返回主题标题。

在Posts.php中将代码更改为多对多关系:

public function post_topics()
{
    return $this->belongsToMany('App\Topics', 'posts_topics', 'post_id', 'topic_id');
}
然后称之为:

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

试试这个并检查它是否适合您。

您有一个多对多关系,以
posts\u topics
作为数据透视表。你可以在这里阅读: