简体   繁体   中英

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:

Product fields

Reviews fields

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:

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

You did not declare the variable $rating prior to using it.

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

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:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM