简体   繁体   English

优化Laravel Backpack nn关系中的查询

[英]Optimize query in Laravel Backpack n-n relationships

I am building a backend panel for a website with Laravel Backpack. 我正在使用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: 在我的CenterCrudController中,我以这种方式定义了一个字段:

$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). 但是使用的查询是SELECT * FROM products ,这是非常昂贵的(表产品具有成千上万条带有25列的记录)。

In this example I only need id and name fields. 在此示例中,我仅需要idname字段。 I am looking for something like Query Builder select() method. 我正在寻找类似查询生成器的select()方法。

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 . 最好的解决方案(由@tabacitu指出)是使用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. 仅当用户单击选择字段时,它不会减慢页面加载速度并发出ajax请求以获取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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