Laravel Eloquent - Get most popular product from summaries

Viewed 320

I am trying to fetch the most popular product of all my summaries. Preverable the name of the product that is the most common among all the summaries.

I have a Summaries table and a products table with a pivot table in between.

The relation is as follows:

Product model

public function summaries()
    {
        return $this->belongsToMany(Summary::class, 'product_summary', 'summary_id','product_id');
    }

Summary model

public function products()
    {
        return $this->belongsToMany(Product::class, 'product_summary', 'summary_id','product_id');
    }

So when let's say of all summaries in the database, most of them have Product A as product. I would like to retrieve the name or object of Product A so I know which product is the most common.

I can't seem to make it work. I tried stuff like

$product = Summary::query()
    ->with(array('products' => function($query) {
        $query->groupBy('name')->select('name');
    }))
    ->get();

Or

$top = Summary::select()->with('products')
->get()->sortByDesc(function($item){
    $item->name;
})->take(1)->get();

But it just does not work. What am I doing wrong?

1 Answers

Your relation is wrong. Edit like below:

Product model:

public function summaries()
    {
        return $this->belongsToMany(Summery::class, 'product_summary', 'product_id', 'summary_id');
    }

then in your controller you can get the product with the most summary as follows:

$product = Product::withCount('summaries')->orderBy('summaries_count', 'desc')->first();
Related