It looks like your relations are like this: Form
hasMany (or hasOne) Entry
hasMany Field
, right?
So you can use a shorthand, that Eloquent provides, for what you are trying to do:
// Form model
public function fields()
{
return $this->hasManyThrough('Field', 'Entry');
}
This way you get all the fields you want providing the Form model, as easy as this:
$fields = Form::find($formId)->fields; // Collection of Field models
Add constraints to the fields:
$fields = Form::find($formId)->fields() // return query builder object...
->where('entry_id', '=', 'value') // ... so you can chain any builder method
->orderBy('something') // for example order by
->get(); // don't forget to return results with get()
edit 2
The easiest way to get both fields and entries, according to your comment, would be:
1 Load fields that match outer where
and entry for each fields matching the inner where
clause:
$fields = $form->fields()->where('x','=','value') // filter fields
->with(['entry' => function ($q) use ($entriesConstraint) {
$q->where('entriesColumn', '=', $entriesConstraint);
}])->get();
2 Load fields that match outer where
and have related entry matching inner where
(and entry for each field):
$fields = $form->fields()->where('x','=','value') // filter fields
->whereHas('entry', function ($q) use ($entriesConstraint) {
$q->where('entriesColumn', '=', $entriesConstraint);
})->with('entry')
->get();
whereHas
and with
mix:
User::whereHas('categories', function ($q) {
$q->where('name','like','%lo%'); // first constraint to fetch entries
})->with(['categories'=>function($q){
$q->where('name','like','%o%') // another constraint for processing related model
->selectRaw('categories.id as id,avg(categories.id) as avg') // raw for fancy aggregate
->groupBy('category_user.user_id'); // group by for aggregate
}])->get();