按用户名字或姓氏或公司名称进行过滤?

时间:2017-01-18 08:39:42

标签: laravel laravel-5 laravel-5.2

我有这个问题:

  public function getResultCommentsWithArticle($comment,$name,$article_title,$orderBy){
        $default_language = Languages::where('default',1)->first();
        $default_language_id = $default_language->id;
        $comments = ArticleComments::orderBy($orderBy,'desc')
                    ->with(['user', 'article'])
                    ->whereHas('article.translations', function($q)
                        use($default_language_id,$article_title) {

                        $q->where('language_id', $default_language_id)
                        ->where('title','like','%' . $article_title . '%');
                    })->where('comment','like','%' . $comment . '%')->paginate(10);

        return $comments;
      }

我有这种关系:

用户:

  public function personal_user()
    {
        return $this->morphOne('App\Models\PersonalUser', 'userable');
    }

    public function business_user()
    {
        return $this->morphOne('App\Models\BusinessUser', 'userable');
    }

当我从$name获取文字名称时,我想检查user->personal_user->first_nameuser->personal_user->last_nameuser->business_user->company_name中是否存在该文字,因为我正在制作过滤器。任何建议我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

尝试这是否适合您

$comments = ArticleComments::orderBy($orderBy, 'desc')
            ->with([
                'article',
                'user' => function ($user) use ($name) {
                    $user->whereHas('personal_user', function ($personalUser) use ($name) {
                        $personalUser->where(function ($q) use ($name) {
                            $q->orwhere('first_name', 'like', '%' . $name . '%')
                                ->orwhere('last_name', 'like', '%' . $name . '%');
                        });
                    })->whereHas('business_user', function ($businessUser) use ($name) {
                        $businessUser->where(function ($q) use ($name) {
                            $q->orwhere('company_name', 'like', '%' . $name . '%');
                        });
                    });
                }
            ])->whereHas('article.translations', function ($q) use ($default_language_id, $article_title) {
                $q->where('language_id', $default_language_id)
                    ->where('title', 'like', '%' . $article_title . '%');
            })->where('comment', 'like', '%' . $comment . '%')->paginate(10);

        return $comments;