使用astrotomic/laravel-translatable时如何用Livewire搜索可翻译产品标题
问题原因
你原有代码的 when 闭包中直接调用 where('title') 是查询主表 products 的字段,而 title 实际存储在关联的 product_translations 翻译表中,主表不存在该字段,因此查询无法生效。
可行解决方案
提供两种实现方式,可根据需求选择:
方案1:使用扩展包内置查询Scope(推荐)
astrotomic/laravel-translatable 已经封装好了翻译字段的查询方法 whereTranslation,直接调用即可,无需手动处理关联逻辑:
$products = Product::select('id', 'category_id', 'price', 'created_at', 'image') ->whereHas('translations', function ($query) { $query->where('locale', app()->getLocale()); }) ->when($this->searchProducts != '', function($query) { // 直接调用扩展包提供的翻译字段查询方法,指定当前语言 $query->whereTranslation('title', 'like', '%'.$this->searchProducts.'%', app()->getLocale()); }) ->with('category:id,name') ->orderBy('category_id', 'asc') ->get();
参数说明:
- 第一个参数:要查询的翻译字段名称
- 第二个参数:查询操作符
- 第三个参数:查询值
- 第四个参数:指定查询的语种,避免匹配到其他语言的翻译内容
方案2:手动合并关联查询条件
如果不想依赖扩展包的封装方法,也可以把title的查询条件放到whereHas的闭包中,直接对翻译表做条件筛选:
$products = Product::select('id', 'category_id', 'price', 'created_at', 'image') ->whereHas('translations', function ($query) { $query->where('locale', app()->getLocale()); // 把搜索条件合并到翻译表的查询逻辑中 if ($this->searchProducts != '') { $query->where('title', 'like', '%'.$this->searchProducts.'%'); } }) ->with('category:id,name') ->orderBy('category_id', 'asc') ->get();
性能优化建议
如果产品数据量较大,建议给 product_translations 表的 title 字段添加前缀索引或者全文索引,优化模糊查询的效率。
内容的提问来源于stack exchange,提问作者Sead Silajdzic
相关产品推荐
相关产品推荐

