How can I improve my method?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
10 views
The task is to display all products from table products and each product category. Many-to-many.
There is a controller named ProductController code:
public function getPart() { $cat2prod = []; $idArr = []; $result= Product::paginate(8)->toArray(); foreach ($result['data'] as $productInfo) { $idArr[] = $productInfo['id']; } $products = Product::find($idArr); foreach ($products as $product){ $cat2prod[$product['id']] = $product->categories->toArray(); } foreach ($result['data'] as $ind => $productInfo) { $result['data'][$ind]['categories'] = $cat2prod[$productInfo['id']]; } return $result;


Model :
class Product extends Model { public function categories() { return $this->belongsToMany('App\\Category','product_categories'); } }


Now everything works, the controller gives the desired array to the database but runs 11 queries. I would like to know how to improve the method without changing the structure of the answer.

$result= Widget::with('categories')->paginate(8); - help.
by | 10 views

1 Answer

0 like 0 dislike
It is better to use with.
$result = Product::paginate(8)->with('categories')->toArray();
by

Related questions

0 like 0 dislike
5 answers
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked Aug 9, 2019 by Hose1021
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
35,405 users