【发布时间】:2018-12-15 11:07:59
【问题描述】:
利用应用程序上的搜索框,数据库有2个表格,如下所示:
________________
|**Services**
________________
|=>id
|=>name
|=>description
|=>other_columns
________________
和:
________________
|**Products**
________________
|=>id
|=>name
|=>description
|=>service_id
|=>other_columns
________________
=>每个服务包含许多产品
=>由于搜索框的形式:
用户可以搜索 products 的单词并可选地选择一个服务,因此,我用来检索结果的 eloquent:
-
如果用户没有选择特定服务进行搜索:
$data = Product::where('name','like',"%$search_value%") ->orWhere('description','like',"%$search_value%") ->orWhere('description_long','like',"%$search_value%") ->paginate($items_per_page); -
如果用户确实选择了特定服务:
$data = Product::where([ ['name','like',"%$search_value%"], ['service_id','=',"%$service%"], ]) ->orWhere([ ['description','like',"%$search_value%"], ['service_id','=',"%$service%"], ]) ->orWhere([ ['description_long','like',"%$search_value%"], ['service_id','=',"%$service%"], ]) ->paginate($items_per_page);
模型关系如下:
-
产品型号:
public function service(){ return $this->belongsTo(Service::class); } -
服务型号:
public function products(){ return $this->hasMany(Product::class); }
在这两种情况下,$data 始终包含所有产品行。如何获得正确的结果?
【问题讨论】:
-
用whereRaw代替where。
-
我已经阅读了
whereRaw的文档,但是你能解释一下区别吗? -
WhereRaw() 是 Laravel 查询构建器的一个函数,它将您的输入原样放在 SQL 查询的 where 子句中。将其视为 where() 函数,其输入参数在插入查询之前不会被处理。
-
为什么还要在
=行中使用百分号? -
为什么 service_id 在这些
['service_id','=',"%$service%"]中有%?不应该是这样['service_id','=',$service]吗?
标签: laravel laravel-5 model eloquent