我正在尝试在Laravel创建我的第一个项目。我有表urls
和reviews
,每个网址都有很多评论。在索引视图中,我想列出所有网址及其最新的2条评论。
模型网址
public function reviews()
{
return $this->hasMany('App\Review');
}
模特评论
public function url()
{
return $this->belongsTo('App\Url');
}
类UrlController
class UrlController extends Controller
{
public function index()
{
// here I would need to get all urls with latest two reviews for each url
$urls = URL::all();
return view('urls.index')->with('urls', $urls);
}
}
查看索引
@foreach ($urls as $url)
<li>
// Echo url name
{{ $url->url }}
// Here I need to list 2 reviews
// Something like...
@foreach ($url->reviews as $review)
$review->text
@endforeach
</li>
@endforeach
我是否通常正确设置了代码?
1.try - UrlController中的此代码适用于网址,而非其评论。
$urls = URL::with('reviews')->orderBy('created_at')->take(2)->get();
2.try 此代码将限制所有已提取评论的数量,在这种情况下,只有第一个网址会收到评论,而其他评价将为零。
$urls = URL::with([
'reviews' => function($q){
$q->orderBy('created_at', 'asc');
$q->limit(2);
}
])->get();
答案 0 :(得分:1)
在模型中添加范围:
public function scopeLatestFirst($query)
{
return $query->orderBy('created_at', 'asc')->limit(2);
}
并致电:
@foreach ($url->reviews()->latestFirst()->get() as $review)
$review->text
@endforeach
有关scopes
的更多信息
答案 1 :(得分:0)
尝试使用相关限制:
public function latestReviews()
{
return $this->hasMany('App\Review')->orderBy('created_at', 'asc')->limit(2);
}
然后加载这个关系:
$urls = URL::with('latestReviews')->get();