2017-08-01 84 views
0

我正在为Laravel Backpack网站构建后端面板。这真的很好,但我注意到关系查询非常昂贵。在Laravel Backpack n-n关系中优化查询

我有两个模型:产品中心与他们之间的多对多关系。在我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... 
]); 

它正常工作,呈现出相关车型选择多场。但是使用的查询是SELECT * FROM products,这是非常昂贵的(表产品有大约25列的数千条记录)。

在这个例子中,我只需要id名称字段。我正在寻找类似查询生成器select()的方法。

有没有一种方法来优化这种类型的查询?

在此先感谢!

+0

你试过用get来选择它吗? - > get(['id','name']) –

+0

@AshishPatel:谢谢,但我不知道如何使用它。方法'CrudPanel :: get()'不存在。你能解释一下吗? – Diego

+0

我认为[select2_from_ajax字段](https://laravel-backpack.readme.io/docs/crud-fields#section-select2_from_ajax)非常适合你。 – tabacitu

回答

1

不知道这是否真的是一个答案,但我会发布它。

最好的解决方案(正如@tabacitu指出的那样)是使用select2_from_ajax field。它不会减慢页面加载速度,并且仅在用户单击选择字段时发出ajax请求才能检索数据。