Livewire渲染Select字段过慢问题求助
问题:Livewire嵌套渲染自关联Location数据性能瓶颈
我在使用Livewire时遇到性能问题:自关联的locations表存储了国家、城市、城镇、子城镇、街区数据,通过parent_id关联层级。查询数据的执行时间不到1秒,但选择城市后,视图中通过嵌套forelse渲染包含城镇、子城镇、街区的Select选项列表耗时6-7秒。注释Select列表部分后系统运行正常。
数据获取方法
public function updatedSelectedCity($value) { if ($value != NULL || $value != "") { $city = Location::findOrFail($value); if ($city) { $this->lat = $city->lat; $this->long = $city->long; $this->dispatchBrowserEvent('load-map', ['lat' => $this->lat, 'long' => $this->long]); } $this->state['city_id'] = $value; $this->towns = Location::where('parent_id',$city->id) ->where('level',2) ->with('child') ->where('active', 1) ->get(); } else { $this->state['city_id'] = NULL; $this->state['town_id'] = NULL; $this->selectedTown = NULL; $this->state['sub_town_id'] = NULL; $this->selectedSubTown = NULL; $this->state['f_s_town_id'] = NULL; $this->selectedFSTown = NULL; $this->sub_towns = NULL; $this->fs_towns = NULL; $this->towns = NULL; $this->lat = NULL; $this->long = NULL; } }
视图代码
<div class="col-sm-9 col-md-9 col-lg-9 col-xl-9 col-xxl-9"> <div class="form-group city-group"> <select id="selectTown" style="width: 251px;!important" class=" js-example-basic-single form-control select-box" wire:model="selectedTown"> <option value="" selected>Select a Town</option> @if($towns) @foreach($towns as $t) @forelse ($t->child as $sub_town ) @forelse ($sub_town->child as $block ) <option value="{{$block->id}}">{{$block->name}}, {{$sub_town->name}}, {{$t->name}}</option> @empty <option value="{{$sub_town->id}}">{{$sub_town->name}}, {{$t->name}}</option> @endforelse @empty <option value="{{$t->id}}">{{$t->name}}</option> @endforelse @endforeach @endif </select> </div> </div>
模型代码
class Location extends Model { use HasFactory; function parent() { return $this->belongsTo(Location::class, 'parent_id'); } public function child() { return $this->hasMany(Location::class, 'parent_id'); } public static function generateSlug($title) { $slug = Str::slug($title); if (self::whereSlug($slug)->count() > 0) { $count = 1; while(self::whereSlug("$slug-$count")->count() > 0) { $count++; } return "$slug-$count"; } return $slug; } }
内容的提问来源于stack exchange,提问作者ayazBAM
相关产品推荐
相关产品推荐

