【问题标题】:Laravel translationsLaravel 翻译
【发布时间】:2022-01-01 21:24:51
【问题描述】:

谁能告诉我如何搜索(使用 livewire)具有可翻译标题的产品? 目前,我正在使用astrotomic/laravel-translatable 包。 翻译工作得很好,我可以静态提取正确的数据,但是当我尝试搜索它时,我遇到了一个问题,因为包期望在不同的表中而不是在主 products 表中具有标题。

这里是代码sn-ps。

可翻译的产品字段表

Schema::create('product_translations', function (Blueprint $table) {
        $table->id();
        $table->string('locale')->index();
        $table->foreignId('product_id')->constrained()->onDelete('cascade');
        $table->string('title');
        $table->timestamps();
    });

主要产品表

Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->foreignId('category_id')->constrained()->onDelete('cascade');
        $table->foreignId('user_id')->constrained()->onDelete('cascade');
        $table->timestamps();
    });

在第一个表中我只需要放置可以翻译的数据,在主产品表中我必须只放置不需要翻译的数据

只是不写创建产品等的整个过程。我将简要说明它是如何工作的。

当我创建 1 个产品时,它将遍历 config.app 可用的语言环境并为所有语言创建相同的产品(相同的标题),然后我们可以选择不同的语言并根据它进行翻译。

当我想提取静态数据时,它看起来像这样:

$products = Product::select('id', 'category_id', 'price', 'created_at', 'image')
        ->whereHas('translations', function ($query) {
            $query->where('locale', app()->getLocale());
        })
        ->with('category:id,name')
        ->orderBy('category_id', 'asc')
        ->get();

现在我想用 livewire 进行实时搜索,但不能像这样提取标题:

$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->where('title', 'like', '%'.$this->searchProducts.'%');
        })
        ->with('category:id,name')
        ->orderBy('category_id', 'asc')
        ->get();

因为标题在不同的表中。

有什么想法吗? 谢谢

【问题讨论】:

    标签: php laravel laravel-livewire


    【解决方案1】:

    我没有测试过,但可以工作

    $products = Product::select('id', 'category_id', 'price', 'created_at', 'image')
            ->whereHas('translations', function ($query) use ($this->searchProducts) {
                if($this->searchProducts) {
                    $query->where('locale', app()->getLocale());
                    $query->where('title', 'like', '%'.$this->searchProducts.'%');
                }
            })
            ->with('category:id,name')
            ->orderBy('category_id', 'asc')
            ->get();
    

    【讨论】:

    • 谢谢!这非常有效,只需要添加一个小改动,否则 laravel 会抱怨语法。而不是$this->searchProducts,我们需要创建一个新变量,例如$searchedProducts = $this->searchProducts,并在我们应该使用$this->searchProducts的地方使用它。除了这个小问题,这是正确的解决方案,将被接受:)
    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 2016-10-27
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多