Home > Software engineering >  Order three different and unrelated models in laravel
Order three different and unrelated models in laravel

Time:07-26

I have three different models and I want to filter them and return them in the same object by creation date. The problem is that the filter must be applied on all models at once and not on each model successively.here are my three models, I don't know how to continue, need help

$quick = Model::with('user')->orderByDesc('id')->get();
$simple = Models::with('user')->orderByDesc('id')->get();
$suivi = Modelss::with(['user', 'position'])->orderByDesc('id')->get();

CodePudding user response:

If there is no link in between the models and you want to retrieve data by ordering them all together. You need to use Collections for this.

What you can do after your 3 line of code is:

$quickSimpleMerged = $quick->merge($simple);
$merged = $quickSimpleMerged->merge($suivi);

$result = $merged->all();

Now that you have 1 collection including all data from 3 models of yours, you can simply run:

$result->sortByDesc('created_at');
  • Related