我正在为一个带有Laravel Backpack的网站构建后端面板。这真的很好,但我注意到关系查询非常昂贵。
我有两个模型:产品和中心,它们之间有多对多的关系。在我的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' => 'AppModelsProduct', // foreign key model
'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
],
// More fields...
]);
它工作正常,显示具有相关模型的选定多个字段。但是使用的查询是SELECT * FROM products
,这是非常昂贵的(表产品有数千条记录,大约 25 列(。
在这个例子中,我只需要id和name字段。我正在寻找类似查询生成器select()
方法的东西。
有没有办法优化这种类型的查询?
提前感谢!
不确定这是否真的是一个答案,但我还是会发布它。
最好的解决方案(如@tabacitu所指出的(是使用select2_from_ajax field
。它不会减慢页面加载速度,并且仅在用户单击选择字段时才发出 ajax 请求来检索数据。