laravel - 如何使用静态值从表中搜索值
问题描述
我成功地从表中搜索绝对值。当我使用“4”之类的值进行搜索时,结果就会显示出来。这是我在模型中的代码:
public static function scopeSearch($query, $searchTerm)
{
return $query->where('experience', 'LIKE', '%' . $searchTerm . '%');
}
目前,我正在4
从表中获取值。另外,我有一个静态值,即years
. 现在,我只希望当我搜索时4 years
它也会显示 4 的结果。是否可以在搜索时添加像年这样的静态值。如果可能的话,请帮帮我。
提前致谢。
解决方案
先按空间爆炸$searchTerm
,然后用 orWhere 和 like。
在你的模型中首先cities
建立这样的关系我不知道你的确切结构:
public function cities()
{
return $this->hasMany(City::class,'job_id','city');
}
然后在这样的查询中使用它:
public static function scopeSearch($query, $searchTerm)
{
if(!is_null($searchTerm)){
$words = explode(' ',$searchTerm);
return $query->Where(function ($q) use($words) {
foreach ($words as $word){
$q->orwhere('experience', 'like', '%' . $word .'%');
}
})->orWhere(function ($q) use($words) {
foreach ($words as $word){
$q->orwhere('job_title', 'like', '%' . $word .'%');
}
})->orWhere(function ($q) use($words) {
$q->WhereHas('cities',function ($qe) use($words) {
foreach ($words as $word){
$qe->orwhere('cities.city', 'like', '%' . $word .'%');
}
});
});
}else{
return $query->Where('experience','');
}
}
我认为有更好的解决方案,但这是我现在发现的。
推荐阅读
- sql - 基于 Excel 中的变量的 Excel VBA 到 SQL 存储过程失败
- cmake - CMAKE 定义依赖
- python - 将空字符串转换为浮点数
- macos - OpenSSL 256 位 AES CBC 输入 - 读取输入文件时出错
- java - 如何使用 java 运行 Oracle .sql 文件
- rest - 如何从 Microsoft Planner 获取所有用户数据?
- reactjs - 无法调整 SVG 元素的大小
- c++ - unique_ptr
- javascript - 如何根据图表js中的值使用段属性为线条/边框颜色着色?
- python - Python“MySQL 错误 [-1]:执行操作失败;无法处理参数”