请问如何查询每个分类下的前 N 条记录?
class ArticleCategory extends Model
{
public function articles()
{
return $this->hasMany('App\Models\Article', 'category_id', 'id');
}
}
$category->with([
'articles' => function ($query) {
$query->limit(6);
}])->get();
SQL: select * from `articles` where `articles`.`category_id` in ('1', '2', '3', '4', ......) limit 6
请问该怎样查询?
我是这样解决的
ArticleCategory::whereIn('id', [1, 2, 3])->with(['articles' => function ($query) {
$table = $query->getRelated()->getTable(); //获取当前依赖表名称
$query->whereRaw('( SELECT COUNT(*) FROM `' . $table . '` AS `temp` WHERE `' . $table . '`.`category_id` = `temp`.`category_id` AND `' . $table . '`.`id` > `temp`.`id`) <= 10'); //10获取10条记录 (table.id > temp.id) >号ID从小到大,<号获取最新的
}])->get();
推荐文章: