skip to Main Content

I have a model with four relations like as below

 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) {};

But when i search with field name CustomFormsform_name it is giving me error

multi part identifier could not be identifed. Any idea I can search with any parameter including all 4 relationships. Currnetly whereRelation is accepting only function at a time.

3

Answers


  1. to search through relation you need to use whereHas foreach relation take look here

    Login or Signup to reply.
  2. From your Situation I understand that You can achieve the result by defining relation column on which you want to filter. Here Is My Example Code.

    $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.'%');
    }
    
    Login or Signup to reply.
  3. You’ll want to use ->whereHas(): docs here.

    $models = YourModel::whereHas('custform_formfields', function (Builder $query) {
        $query->where('some_field', 'like', '%some_search_term%');
    })->whereHas('custform_fieldtype', function (Builder $query) {
        $query->where('some_other_field', 'SOME_VALUE');
    })->whereHas(...) // whatever other conditions you want here...
    ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search