如何通过从结果中减去数字来计算嵌套关系和附加字段
Posted
技术标签:
【中文标题】如何通过从结果中减去数字来计算嵌套关系和附加字段【英文标题】:How to count nested relationship and append field by substracting number from result 【发布时间】:2020-12-26 18:59:37 【问题描述】:我有从数据库获取服务的示例查询:
$services = City::select('id', 'name')->has('services')
->with([
'services:id,title,description',
'services.reviews'
])
->get()->each(function($city)
return $city->services->each(function($service)
$service->setRelation('reviews', $service->reviews->take(3));
return $service;
);
);
这会返回一些 json 响应:
[
"id": 1,
"name": "London",
"services": [
"id": 2,
"title": "Service title",
"description": "Service description",
"reviews": [
"id": 1,
"author": "John Doe",
"description": "Service review description"
]
]
]
默认情况下,在我的案例中,我对每项服务都有 3 条评论。如何将剩余评论数量附加到每项服务。为此,首先需要计算服务的评论总数并减去 3,如果结果大于 0,则分配一个值,否则分配一个值 0。
【问题讨论】:
你试过 laravelwithCount()
@KamleshPaul 是的,我试过了,但在我的情况下,它会计算所有评论,而不是附加到嵌套关系服务
【参考方案1】:
试试这个可能会奏效
我添加的小计算可能会起作用
https://laravel.com/docs/7.x/queries#ordering-grouping-limit-and-offset
offset()
计算取3
$services = City::select('id', 'name')->has('services')
->with([
'services:id,title,description',
'services.reviews'
])->get()->each(function ($city)
return $city->services->each(function ($service,$key)
$offset = $key*3; // so get 3 multiple
$service->setRelation('reviews', $service->reviews->offset($offset)->take(3));
return $service;
);
);
【讨论】:
以上是关于如何通过从结果中减去数字来计算嵌套关系和附加字段的主要内容,如果未能解决你的问题,请参考以下文章