Order by own key

Published 3 weeks ago by fwartnerAY

Hey everyone..

I have a question regarding to Eloquents orderBy method..

Szenario: I have a user. This user belongs to a unit. Now on the unit page, i want to to show all units but the unit of the user should be on top.

How do i order this?

Best Answer (As Selected By fwartnerAY)
vladshoob

Maybe, you can sort collection.

// get units of user
$user_units = $user->units;

// delete them from $units collection

// prepend user's units to $units collection
$units->prepend($user_units);

RamjithAp

Try this

$units= Units::with('users')->get()->sortBy(function($unit)
{
    return $unit->users->count();
});

OR

$units= Units::withCount('users')->orderBy('users_count', 'desc')->paginate(10);

For more details refer this thread https://stackoverflow.com/questions/24208502/laravel-orderby-relationship-count/24208979#24208979

fwartnerAY

This is what i have so far.. My application contains a lot of users and units.. A user belongs to a unit.

Normally, the units are ordered by name. Wich is fine for me. But right now, i want to have the unit of the authenticated user right on top of all units. After the unit of the user, i want the other units..

Unit Model:

/**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function users()
    {
        return $this->hasMany(User::class, 'unit_id');
    }

User Model:

/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function unit()
    {
        return $this->belongsTo(Unit::class, 'unit_id');
    }

In the UnitController:

$units = Unit::with('users', 'circles', 'articles', 'techlead', 'productlead')
                ->withCount('circles')
                ->orderBy('name')
                ->paginate();
vladshoob

Maybe, you can sort collection.

// get units of user
$user_units = $user->units;

// delete them from $units collection

// prepend user's units to $units collection
$units->prepend($user_units);

fwartnerAY

@vladshoob a user only belongs to one unit. With prepend i get no output =/

fwartnerAY

Got it!

fwartnerAY

UPDATE: Doesn´t work.. It was just because i found a unit on top, thats always on top.. ^^

vladshoob

Update.

$user_unit = Unit::first();

$units = Units::all();
$units = collect($units);

$key = $units->search($user_unit);
$units->pull($key);

$units->prepend($user_unit);
dd($units); // you will have in $units all your Units with prepended $user_unit

Ahh.. you have pagination...

vladshoob

I beleive it is the answer. But I'm not strong in queries.

https://laracasts.com/discuss/channels/eloquent/custom-orderby-in-laravel-query-builder

Please sign in or create an account to participate in this conversation.