2017-08-01 38 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請求才能檢索數據。