我这里有一个Livewire渲染函数,根据在文本框上搜索的内容显示记录。它工作得很好,并以自动完成的方式给我结果。但是,当我添加这行->orWhere('qty_on_hand', '!=', 0)
时,它会停止自动完成搜索。
<?php
namespace AppHttpLivewire;
use LivewireComponent;
use AppModelsProduct;
class LoadInStockProducts extends Component
{
public $searchTerm;
public $amount = 10;
protected $listeners = [
'load-more' => 'loadMore'
];
public function loadMore()
{
$this->amount = $this->amount + 10;
}
public function render()
{
$searchTerm = '%' . $this->searchTerm . '%';
$products = Product::orderBy('name')->where('code', 'like', $searchTerm)
->orWhere('name', 'like', $searchTerm)
->orWhere('description', 'like', $searchTerm)
->orWhere('qty_on_hand', '!=', 0)
->paginate($this->amount);
$this->emit('productStore');
return view('livewire.load-in-stock-products', ['products' => $products]);
}
}
即使在->orWhere('qty_on_hand', '!=', 0)
条件下,我如何使自动完成搜索工作?另外,另一个问题,我试过这个->orWhere('srp', '!=', 0.00)
,它不工作。我怎样才能使它为浮点类型工作?顺便说一下,srp
字段是浮点类型。
任何帮助都非常感谢。
在我看来,您想要生成一个查询,在其中搜索给定字段,并且只显示手头有数量的记录—在原始SQL中看起来像这样,
SELECT *
FROM products
WHERE (
code LIKE '%searchterm%'
OR name LIKE '%searchterm%'
OR description LIKE '%searchterm%'
)
AND qty_on_hand != 0
ORDER BY name
注意对代码/名称/描述的搜索是如何在其自己的组中进行的,并且您要查找和中的任何一个匹配。其中数量不等于0。
在Laravel中,这意味着你必须使用闭包对查询进行分组。
$products = Product::where(function($query) use ($searchTerm) {
return $query->where('code', 'like', $searchTerm)
->orWhere('name', 'like', $searchTerm)
->orWhere('description', 'like', $searchTerm);
})
->where('qty_on_hand', '!=', 0)
->orderBy('name')
->paginate($this->amount);
如果你有其他条件,你可以引入更多的组,比如有两个where()
和一个闭包,其中的查询使用orwhere()
。
$products = Product::where(function($query) use ($searchTerm) {
return $query->where('code', 'like', $searchTerm)
->orWhere('name', 'like', $searchTerm)
->orWhere('description', 'like', $searchTerm);
})
->where(function($query) {
return $query->where('qty_on_hand', '!=', 0)
->orWhere('srp', '!=', 0);
})
->orderBy('name')
->paginate($this->amount);