Eloquent ORM Eager-loading Single entries in many ways

Background

I have a List model that owns and has many subscribers. And, of course, the Subscriber who owns and has many List.

Problem

I want to download all subscribers from several lists. BUT, I am only interested in individual subscribers, since a subscriber can and does belong to several lists.

My attempt

I used the distinct() method, but it did not bring any joy. And I can also scroll through the result set to manually cut duplicates. Just wondering if there is a way to let Laravel do the dirty work for me?

the code

  $lists = Input::get('listsarray'); $addresses = Addressbook::with(array('subscribers' => function($query) { $query->where('active', '=', 1); // $query->distinct(); //This didn't work }))->whereIn('id', $lists)->get(); 
+4
source share
1 answer

Getting Unique Subscribers Through Consolidation

I will try to explain this using Lists instead of the Adressbook , because I could not understand your model and what could lead to further confusion.

If I understand your comments correctly, you are trying to get all unique subscribers that have associations with id IN listarray . In this case, Eager Loading is not suitable for this. The desired download serves to preload the associations for the model so that they can be used later. In your case, you do not extract the Lists and their Subscribers , but the unique Subscribers themselves.

 $lists = Input::get('listsarray'); $subscribers = Subscriber::join('list_subscriber', 'list_subscriber.subscriber_id', '=', 'subscribers.id') ->whereIn('list_subscriber.list_id', $lists) ->groupBy('list_subscriber.subscriber_id') ->get(array('subscribers.*')); 

If you also want to get all the lists associated with such subscribers, you can do this:

 // Simply include a with('lists') and Eloquent will eager load them $subscribers = Subscriber::with('lists') ->join('list_subscriber', 'list_subscriber.subscriber_id', '=', 'subscribers.id') ->whereIn('list_subscriber.list_id', $lists) ->groupBy('list_subscriber.subscriber_id') ->get(array('subscribers.*')); 

Lively Download

If it is simply a matter of increasing productivity, you do not need to use different ones, Laravel already does this. Eloquent behaves like this:

  • Selects all Lists .
  • Iterate through Lists creating an array of unique list_ids
  • Selects all list_subscribers with WHERE list_id IN (X, Y, Z)
  • Iterate through all list_subscribers building an array of unique subscriber_id
  • Selects all Subscribers using WHERE id IN (X, Y, Z)
+5
source

Source: https://habr.com/ru/post/1498594/


All Articles