B
B
bubji92018-05-03 13:37:29
Laravel
bubji9, 2018-05-03 13:37:29

How can the method be improved?

The task is to display on the page all products from the table of products and for each product of its category. Many-to-many relationship.
There is a ProductController controller, it contains the 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 is working, the controller gives the required array, but 11 queries are executed to the database. I would like to know how you can improve the method without changing the structure of the answer.
$result= Widget::with('categories')->paginate(8); - helped.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Dergachov, 2018-05-03
@bubji9

It's better to use with.

$result = Product::paginate(8)->with('categories')->toArray();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question