samedi 23 février 2019

How to sort the results by a relation hasone Laravel and Eloquent

I know that to order the elements of a relation, we use with and pass a function to tell Eloquent to order by a specific column of the relation

 $query->with(['relation' => function ($query) { 
     $query->orderBy('columName', 'ASC');
 }]);

But I have a hasOne relationship, what I want is to order the elements of the parent model through the field of the relationship. How can I do this?

I tried to do something dynamic and that works for different models and relationships

// ordercolumn -> relation.column
// order -> ASC or DESC
$pos = strpos($ordercolumn, '.');
 if ($pos !== false) {
 $column = explode(".", $ordercolumn);
  return $query->whereHas($column[0], function ($query)  use ($column,$order){ 
      $query->orderBy($column[1],$order ?? 'ASC');
   })->paginate($perPage);
 }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire