【发布时间】:2016-09-29 03:19:23
【问题描述】:
我有一个 API 端点,我想在其中发送文章的所有相关数据。我有表users、comments、articles。 Users 表有字段id、first_name、last_name,表comments 有字段id、article_id、user_id。关系定义如下:
文章型号:
public function comments()
{
return $this->hasMany('App\Comment');
}
用户模型:
public function comments()
{
return $this->hasMany('App\Comment');
}
评论模型:
public function user()
{
return $this->belongsTo('App\User');
}
现在在我的函数中,我正在获取文章,然后创建一个包含有关 cmets 信息的数组。我应该为每条评论获取用户 first_name 和 last_name,但我不确定如何执行此操作,以及在从 eloquent 查询中获取集合时是否可以执行此操作?
这是函数:
$result = Article::where('publish', 1)->orderBy('created_at', 'desc')->paginate(15);
foreach($result as $article){
$articles[$article->id] = $article;
$articles[$article->id]['comments'] = $article->comments()->get();
}
return $articles;
【问题讨论】: