[英]How to optimize the load of many data options into a select box from db passed via a variable in Laravel 5.7?
我正在用數據庫select box
的數據填充select box
。 事實是里面有139659個元素(僅從單個列獲取)。
我試了一次,我猜所有的數據都被加載了,當然我的應用程序加載了所有的東西也很慢。
那么, 如何優化從中獲取數據呢? 我將使用select2
獲得更多功能,盡管我認為我首先需要解決如何加載數據的問題。
我的代碼:
<div id="inputs-postal">
<div class="form-group">
<select name="codigoPostal" id="select-cp">
@foreach ($cpostales as $cp)
<option value="{{ $cp->postal_code }}">{{ $cp->postal_code }}</option>
@endforeach
</select>
</div>
</div>
控制器:
public function create()
{
// Toma los estados de la base de datos.
$estados = DB::connection('db_postalcodes')
->table('state')
->groupBy('state')
->get();
$cpostales = DB::connection('db_postalcodes')
->table('postal_code')
->get();
// El with hace que se adjunten variables al view.
return view('admin.posts.create')->with('estados', $estados)->with('cpostales', $cpostales);
}
如果您不介意使用jQuery UI,一種選擇是使用帶有文本字段的jQuery自動完成功能 ,而不是下拉菜單。 這是我使用的一些工作代碼。
在您的控制器中,創建一個返回少量郵政編碼的函數:
<?php
use Response;
...
public function searchPostalCode(Request $request)
{
$term = $request->input('term');
$results = [];
$queries = DB::table('db_postalcodes')
->where('postal_code', 'LIKE', '%'.$term.'%') //search 'postal_code' column
->take(5)->get(); // get 5 results
foreach ($queries as $query) {
$results[] = ['id' => $query->id, 'value' => $query->name];
}
return Response::json($results);
}
在Laravel的網絡路線中為其定義路線
Route::get('/searchPostalCode', 'PostalCodeController@searchPostalCode');
然后,在刀片模板中添加此代碼段
<input id="postal-code" type="text" name="postal-code">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
<!--
$( "#postal-code" ).autocomplete({
source: "{{URL('/searchPostalCode')}}",
minLength: 3,
select: function(event, ui) {
$('#postal-code').val(ui.item.value);
}
});
//-->
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.