senty
senty

Reputation: 12847

Ordering Multiple Eloquent Models

I have 3 tables, category, rss, and rss items. Category has list of rsses under it, and each rss has its own feeds. What I am trying to achieve is ordering them by publishing date of each feed item.

To be clear, example:

Category: dogs > 3x RSS assigned to dogs category > each RSS has 30 feed items.

And each feed item has its pub_date.


What I am trying to do is using the category id, getting all feed items and ordering them by pub_date.

What I tried:

$categoryId = Category::where('name', $category)->first()->id;
$rsses = RSS::where('category_id', $categoryId)->get();

// rsses is now a collection of each RSS arrays.

Now, I want to get the feedItems, ordered by pub_date. I tried using a forloop:

$rssItems = [];

foreach ($rsses as $rss) {
   array_push($rssItems, RssFeed::where('rss_id', $rss->id)->orderBy('pub_date', 'asc')->get());
}

This gives me an array of each rss feed items, ordered in its own rss feed, and not a bulk list.

Instead, I want to get 1 array or object, with all feed items unionised in that array, and ordered by pub_date. My method brought me an array of arrays for each rss feed, and each feed items are ordered by themselves and not globally.

Upvotes: 1

Views: 34

Answers (1)

Rahul
Rahul

Reputation: 18557

What you can do is,

$rsses = RSS::where('category_id', $categoryId)->pluck('id');

this will return you an array of all rsses

And then fire,

RssFeed::whereIn('rss_id', $rsses)->orderBy('pub_date', 'asc')->get();

This should give you bulk data.

Give it a try, it should work.

Upvotes: 1

Related Questions