-1

for some time i have been trying to figure out how to achieve a custom order in my eloquent (collection?): This is my collection (Notice I did not make use of ->get() because in the latter part of the function, im using this to extend the query/collection)

$ads = Ad::whereIn('ad_type',[2,3,1]); <-- This is my Desired Output as well.

I have multiple Elements in my Ad table with each ad_type.

So i have tried:

$ads1 = Ad::where('ad_type',1);
$ads2 = Ad::where('ad_type',2);
$mergedAds = $ads1->merge($ads2);

But i just get:

'Call to undefined method Illuminate\Database\Query\Builder::merge()'

Next i tried leaving $ads1 as it is and adding:

            $ads2 = sortBy(function($ads) use ($ad_types) {
            return array_search($ads->getKey(), $ad_types);
        });

but well, its not an array so this cant work. Can anyone put me in the right direction? And maybe explain what the difference between Collection, Eloquent Collection and Query might be so i can understand this better. Thank you so much in advance. (Why I ask this question: I have seen people doing collect() or new Collection() and i dont know what this is, neither did I really find out anything useful)

Desory
  • 83
  • 2
  • 11

1 Answers1

2

Regarding this piece of code.

$ads1 = Ad::where('ad_type',1);
$ads2 = Ad::where('ad_type',2);
$mergedAds = $ads1->merge($ads2);

$ads1 and $ads2 are called two QUERIES, not the actual results yet. To get the actual results:

$ads1 = Ad::where('ad_type',1)->get();
$ads2 = Ad::where('ad_type',2)->get();
$mergedAds = $ads1->merge($ads2);

I assume you want to sort the ads by the ad type in the order of 2, 3, 1. I come over this link:

How to define a custom ORDER BY order in mySQL

So in Laravel, this might work:

    $ads = Ad::sortByRaw("FIELD(Language, 2, 3, 1)")->get();
Kevin Bui
  • 2,754
  • 1
  • 14
  • 15
  • Thanks that drove me into the correct direction, but i encountered an error , of which the fix was: sortByRaw(DB::RAW(...)) so i had to use db raw also – Desory Jun 06 '19 at 08:22