简体   繁体   中英

Optimize query in Laravel Backpack n-n relationships

I am building a backend panel for a website with Laravel Backpack. It is really nice, but I have noticed that relationship queries are very expensive.

I have two models: Product and Center with a many to many relationship between them. In my CenterCrudController I have defined a field this way:

$this->crud->addColumns([
    // More fields...
    [      
        'label' => 'Products',
        'type' => 'select2_multiple',
        'name' => 'products', // the method that defines the relationship in your Model
        'entity' => 'products', // the method that defines the relationship in your Model
        'attribute' => 'name', // foreign key attribute that is shown to user
        'model' => 'App\Models\Product', // foreign key model
        'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
     ],
     // More fields...
]);

It works fine, showing a select multiple field with related models. But the query used is SELECT * FROM products , which is highly expensive (table products have thousands of records with about 25 columns).

In this example I only need id and name fields. I am looking for something like Query Builder select() method.

Is there a way for optimizing this type of query?

Thanks in advance!

Not sure if this is actually an answer, but I'll post it anyway.

The best solution (as pointed by @tabacitu) was using select2_from_ajax field . It doesn't slow page load and make an ajax request for retrieving data only when user clicks on the select field.

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