[英]Laravel translations
有人可以告訴我如何搜索(使用 livewire)具有可翻譯標題的產品嗎? 目前,我正在使用astrotomic/laravel-translatable
package。 翻譯工作得很好,我可以靜態地提取正確的數據,但是當我嘗試搜索它時,我遇到了一個問題,因為 package 期望在不同的表中有一個標題,而不是在主products
表中。
以下是代碼片段。
可翻譯的產品字段表:
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 可用的語言環境並為所有語言創建相同的產品(相同的標題),然后我們可以選擇不同的語言並根據它進行翻譯。
當我想提取 static 數據時,它看起來像這樣:
$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();
因為標題在不同的表中。
有任何想法嗎? 謝謝
我沒有測試它但可以工作
$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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.