[英]get all data count from relationship | Laravel
i use laravel:command for function, which is i need to know how many reviews been given to my products, i will capture my database example below:我使用 laravel:命令 function,这是我需要知道我的产品有多少评论,我将在下面捕获我的数据库示例:
i've already declare the relationship which is:我已经声明了以下关系:
App\Models\Product:应用\模型\产品:
public function rev()
{
return $this->hasMany(Reviews::class, 'product_id', 'id');
}
App\Models\Review:应用\模型\评论:
public function prod()
{
return $this->belongsTo(Products::class, 'product_id','id');
}
and this is my command for the function:这是我对 function 的命令:
protected $signature = 'review:product {product_id}';
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
foreach ($products as $key => $value) {
$rating = $value->rev->rating;
}
dd($products);
}
after i run my command it returns this error Error在我运行我的命令后,它返回此错误错误
what i'm expecting is i could get the whole rating of specific id我期望的是我可以获得特定 id 的全部评级
You did not declare the variable $rating prior to using it.您没有在使用变量 $rating 之前声明它。
But there is a much easier approach to your problem, since youve already setup the relationships.但是有一个更简单的方法来解决您的问题,因为您已经设置了关系。
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::find($id);
$ratings = $products->rev->pluck('rating');
dd($ratings);
}
Because of product
can have many revs
, so you can use loop for this因为
product
可以有很多revs
,所以你可以使用循环
foreach ($value->rev as $item) {
$val = $item->rating;
}
if you are expecting to sum up all rating for particular product id, then you should declare initial number for variable $rating
before foreach
, then sum up with +=
operator:如果您希望总结特定产品 id 的所有评分,那么您应该在
foreach
之前声明变量$rating
的初始数字,然后用+=
运算符总结:
public function handle(){
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
$rating = 0;
foreach ($products as $key => $value) {
$rating += $value->rev->rating;
}
dd($rating);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.