eloquent - Laravel - retrieve direct/indirect pivot table subscribers -
i having hard time figuring out in laravel; subscriber relationship have 2 pivot tables:
a subscriber can subscribe question:
question_subscriber id question_id subscriber_id 1 2 3 2 2 4 3 3 1 4 3 2
a subscriber can subscribe user:
user_subscriber id user_id subscriber_id 1 1 6 2 1 7 3 2 1
normal questions table question owner:
questions id question user_id 1 abc? 1 2 xyz? 1 3 123? 2
the pivot relationships setup correctly in models, , can pull out foreach, subscribers question, $question->subscribersquestion $subscriber
, or subscribers user, $user->subscribersuser $subscriber
:
but how can pull out all subscribers belong user (directly or indirectly (through question own))?
for example, these should retrieved subscribers user 1
:
6 // subscribed directly 7 // subscribed directly 3 // subscribed through question 4 // subscribed through question
any idea on efficient way in laravel?
this easiest way:
// assuming setup: user hasmany question user belongstomany user (subscribers - direct) question belongstomany user (subscribers - indirect) // don't need this, since pass reference closure, // clarity let's initialize variable: $indirectsubscribers = null; $user = user::with(['questions.subscribers' => function ($q) use (&$indirectsubscribers) { // indirect subscribers (cost of additional query) $indirectsubscribers = $q->get()->unique(); }])->find($userid); // merge directs subscribers $allsubscribers = $user->subscribers->merge($indirectsubscribers);
Comments
Post a Comment