簡體   English   中英

select2_from_ajax_multiple優化Laravel查詢

[英]select2_from_ajax_multiple optimize query for laravel

我有2張桌子:

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?
]);

據我所知,這就是select2的AJAX功能的工作方式。 每次提交AJAX呼叫時,他們都會發送其收集的所有數據。 不只是添加了什么。 這樣,如果您已經選擇了多個條目,則將為每個條目進行一個SQL調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM