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
作为数据透视表。你可以在这里阅读: