我有两个表第一个表是帖子表,第二个表是 home_posts 表所以我想在home_posts表(post_id)中将post get记录在posts表中。
我在帖子模型中使用了hasMany()关系但没有获得任何记录。我只想要post表中的home_posts表post id记录。我希望家庭邮政表发布表记录。
Post table
+----+-----------------+
| id | title |
+----+-----------------+
| 1 | Post 1 |
| 2 | Post 3 |
| 26 | Post 4 |
| 27 | Post 5 |
| 28 | Post 6 |
| 29 | Post 7 |
| 30 | Post 8 |
| 32 | Post 9 |
+----+-----------------+
home_post table
+----+------------+
| id | post_id |
+----+------------+
| 1 | 28 |
| 2 | 29 |
| 3 | 2 |
+----+------------+
答案 0 :(得分:1)
在发布模型中:
public function home_posts()
{
return $this->hasMany('App\HomePost', 'post_id', 'id');
}
在 HomePost 模型中:
public function post()
{
return $this->belongsTo('App\Post', 'post_id', 'id');
}
通过 home_post 发布:
$homePost = \App\HomePost::find(1);
$post = $homePost->post;
或
$posts = \App\HomePost::has('post')->get();
通过发布获取 home_post :
$post = \App\Post::find(1);
$homePost = $homePost->home_posts;
或
$homePost = \App\Post::has('home_posts')->get();
有关详细信息,请阅读:One To Many
希望它对你有所帮助:)。