andyandy's avatar

How to define eloquent relationships

I have following table structure:

Questionnaires -> Pillars -> Sections -> Questions

And it would be easy to define belongsToMany() relationships between tables to retrieve everything like this:

Questionnaire::with('pillars.sections.questions')->get();

Easy peasy.

Here comes the catch: There's an extra pivot table questionnaire_question that defines which questions questionnaire can have. So you cannot define relationship only between Sections->Questions because it also depends on current questionnaire.

0 likes
2 replies
andyandy's avatar

I think I will abandon this solution via relationships.

MohamedTammam's avatar

You can have conditions while loading the relationship.

Questionnaire::with(['pillars.sections.questions' => fn($q) => $q->has('questionnaire', fn($q2) => $q2->where('...', ...))])->get();

Please or to participate in this conversation.