如何使用eloquen关系从laravel中的post表中获取记录

时间:2017-03-06 04:54:07

标签: laravel-5 eloquent

我有两个表第一个表是帖子表,第二个表是 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          |  
+----+------------+ 

1 个答案:

答案 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

希望它对你有所帮助:)。