【问题标题】:How to apply multiple where condition on laravel eloquent having mutliple models如何在具有多个模型的 laravel eloquent 上应用多个 where 条件
【发布时间】:2023-02-24 21:41:59
【问题描述】:

我有一个有四个关系的模型,如下所示

 public function custform_formfields()
    {
        return $this->hasOne(FormFieldMapping::class,'field_id','field_id');
    }

    public function custform_fieldtype()
    {
        return $this->hasOne(FieldType::class, 'fieldtype_id', 'html_field_type');
    }

    public function custform_forms()
    {
        return $this->hasOne(CustomForms::class,'form_id', 'form_id');
    }

    public function custform_options()
    {
        return $this->hasOne(FormOptions::class,'option_id', 'option_id');
    }

 $model::with('custform_formfields','custform_fieldtype','custform_forms','custform_options')->whereRelation('custform_formfields',function($q) use ($whereArray) {};

但是,当我使用字段名称 CustomFormsform_name 进行搜索时,出现错误

无法识别多部分标识符。任何想法我都可以使用任何参数进行搜索,包括所有 4 个关系。目前 whereRelation 一次只接受函数。

【问题讨论】:

    标签: laravel eloquent laravel-9 eloquent-relationship


    【解决方案1】:

    要搜索关系,您需要使用 whereHas foreach 关系看看here

    【讨论】:

      【解决方案2】:

      根据您的情况,我了解到您可以通过定义要过滤的关系列来实现结果。这是我的示例代码。

      $query = $model::with(['custform_formfields','custform_fieldtype','custform_forms','custform_options']);
      
      $relationSearchFields = ['custform_fieldtype.name','custform_forms.title']; // array of relation columns to search
      
      $search = $request->search; // search parameter from the request
      
      foreach ($relationSearchFields as $field) {
         $relationSearch = explode('.', $field);
         $query->whereRelation($relationSearch[0], $relationSearch[1], 
         'like', '%'.$search.'%');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-28
        • 2014-01-10
        • 2015-01-23
        • 2015-04-07
        相关资源
        最近更新 更多