You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:36:03