代码之家  ›  专栏  ›  技术社区  ›  Hardist

在Laravel的when with wherehas中使用

  •  0
  • Hardist  · 技术社区  · 6 年前

    我有以下问题:

    return Expense::with('descriptions')
        ->when($this->string, function ($query) {
            return $query->where('name', 'LIKE', '%' . $this->string . '%');
        })
        ->orWhereHas('tags', function ($query) {
            $query->where('name', 'LIKE', '%' . $this->string . '%');
        })
        ->get();
    

    我需要的是,使用 whereHas when 不知何故。如果 $this->string 是空的 何处 不应该使用。因为它会把所有 Tag 像这样,我只需要在 $this->字符串 不是空的。

    有没有办法写得很清楚?我不想用if/else检查是否 $this->字符串 设置,然后返回不同的内容。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Mirdrack    6 年前

    自从你 何处 取决于外部变量,最好的方法是用条件语句构造查询,并对变量进行评估。

    不要害怕将查询的构造分为多个步骤,您不需要链接所有内容并返回它。

    它的可读性更高,如下所示:

    $builder = Expense::with('descriptions')
                    ->where('name', 'LIKE', '%' . $this->string . '%');
    
    if ($this->string) {
        $builder = $builder->whereHas('tags', function ($query) {
            $query->where('name', 'LIKE', '%' . $this->string . '%');
        });
    }
    return $builder->get();
    
        2
  •  1
  •   Saman Ahmadi    6 年前

    你想要这样的东西吗?

    return Expense::with('descriptions')
        ->when(!empty($this->string), function ($query) {
            return $query->WhereHas('tags', function ($query) {
                $query->where('name', 'LIKE', '%' . $this->string . '%');
            })
        })
        ->get();