首页 > 解决方案 > 如何使用静态值从表中搜索值

问题描述

我成功地从表中搜索绝对值。当我使用“4”之类的值进行搜索时,结果就会显示出来。这是我在模型中的代码:

public static function scopeSearch($query, $searchTerm)
    {
        return $query->where('experience', 'LIKE', '%' . $searchTerm . '%');
    }

目前,我正在4从表中获取值。另外,我有一个静态值,即years. 现在,我只希望当我搜索时4 years它也会显示 4 的结果。是否可以在搜索时添加像年这样的静态值。如果可能的话,请帮帮我。

提前致谢。

标签: laravel

解决方案


先按空间爆炸$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','');
    }
} 

我认为有更好的解决方案,但这是我现在发现的。


推荐阅读