有人能告訴我如何搜索(使用 livewire)具有可翻譯標題的產品嗎?目前,我正在使用astrotomic/laravel-translatable包。翻譯作業得很好,我可以靜態地提取正確的資料,但是當我嘗試搜索它時,我遇到了一個問題,因為該包希望在不同的表中而不是在主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 可用的語言環境并為所有語言創建相同的產品(相同的標題),然后我們可以選擇不同的語言并基于它進行翻譯。
當我想提取靜態資料時,它看起來像這樣:
$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();
因為標題在不同的表中。
有任何想法嗎?謝謝
uj5u.com熱心網友回復:
我沒有測驗但可以作業
$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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364637.html
