Is it possible to sort the result of the parent Model by the child model? [duplicate]

1

Controller

$menu       = MenuLoginPermission::with('submenu')
            ->where('id_empresa_login', '=', $idUser)
            ->get();

Model MenuLoginPermission

class MenuLoginPermission extends Model
{
    public function menu(){
        return $this->belongsTo('App\Menu', 'id_menu', 'id');
    }
    public function submenu(){
        return $this->hasMany('App\Submenu', 'id_menu', 'id_menu');
    }
}

I'm not able to do the Model Parent order by a ORDER field of the Model Son.

Is this possible?

I tried WhereHas and Eager Loading , but it did not work.

In the latter case I will make a LeftJoin . But first, I wanted to know if you have a solution otherwise.

Parent Model = MenuLoginPermission

Child Model = Menu

Table Field Menu = Order

    
asked by anonymous 07.10.2016 / 17:31

1 answer

3

There is a way to sort with collection result , class collection with the sort

Example:

Code:

$collect = collect(['d' => 2, 'a' => 1, 'z' => 0]);
return $collect->sort(function($a, $b){
    return $a == $b ? 0: ($a > $b ? 1 : -1);
})->toArray();

Exit:

{ "z": 0, "a": 1, "d": 2}

In your code:

  MenuLoginPermission::with('submenu')
   ->where('id_empresa_login', '=', $idUser)
   ->get();
   ->sort(function($p1,$p2)
     {
        $a = $p1->menu->order;
        $b = $p2->menu->order;
        return $a == $b ? 0: ($a > $b ? 1 : -1);
     }, SORT_REGULAR, false)
    ->toArray();

The most natural way would be with leftJoin

MenuLoginPermission::with('submenu')
  ->where('id_empresa_login', '=', $idUser)
  ->leftJoin('submenu', 'submenu.id_menu','=','menuloginpermission.id_menu')  
  ->orderBy('submenu.order','asc')
  ->select('menuloginpermission.*')
  ->get();

There is a way to write an anonymous item with the command with , but the result of sort does not influence the main item .

    
07.10.2016 / 18:17