select2_from_ajax_multiple优化laravel查询

时间:2017-10-05 19:55:50

标签: php mysql laravel laravel-5 backpack-for-laravel

我有两张桌子:

1. Users
2. Tags
  

tags_users是数据透视表

这些表格具有多对多关系。

为什么addField UserCrudController在单个查询中可以访问结果时会发出过多的查询?

示例:

当我编辑具有多个代码的用户时,addField会进行以下查询:

select * from `tags` where `tags`.`id` = '11' limit 1;
select * from `tags` where `tags`.`id` = '13' limit 1;
select * from `tags` where `tags`.`id` = '14' limit 1;
select * from `tags` where `tags`.`id` = '57' limit 1;

我理解select2_from_ajax每次检索新信息时都需要发出一个AJAX请求,但是如何从User对象中获取第一个选择的结果呢?

像这样:User::find(1)->tags。这将返回用户的标签集合,并避免多次查询以获得相同的结果。

这是我的UserCrudController:

http://sandbox.onlinephpfunctions.com/code/023c2eb5749180967efe0a24dbb7125d95815537

它是代码的一部分:

$this->crud->addField([ // Select2Multiple = n-n relationship (with pivot table)
        'label' => 'Tags',
        'type' => 'select2_from_ajax_multiple_custom',
        'name' => 'tags', // the method that defines the relationship in your Model
        'entity' => 'tags', // the method that defines the relationship in your Model
        'attribute' => 'name', // foreign key attribute that is shown to user
        'model' => Tag::class, // foreign key model
        'data_source' => route("search.tags"),
        'placeholder' => "Select a city",
        'minimum_input_length' => 2, // minimum characters to type before querying results
        'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
]);

1 个答案:

答案 0 :(得分:0)

据我所知,这就是select2的AJAX功能如何运作。每次他们提交AJAX呼叫时,他们都会发送已收集的所有数据。不只是添加了什么。因此,如果您已经选择了多个条目,则将为每个条目进行SQL调用...