【发布时间】: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