sql >> Base de Datos >  >> RDS >> Mysql

Cómo ordenar por datos de tabla dinámica en Eloquent ORM de Laravel

Hay 2 formas:una especificando el table.field , otros usan el alias de Eloquent pivot_field si usa withPivot('field') :

// if you use withPivot
public function articles()
{
  return $this->belongsToMany('Article', 'tops_has_posts')->withPivot('range');
}

// then: (with not whereHas)
$top = Top::with(['articles' => function ($q) {
  $q->orderBy('pivot_range', 'asc');
}])->first(); // or get() or whatever

Esto funcionará, porque Eloquent crea un alias en todos los campos provistos en withPivot como pivot_field_name .

Ahora, solución genérica:

$top = Top::with(['articles' => function ($q) {
  $q->orderBy('tops_has_posts.range', 'asc');
}])->first(); // or get() or whatever

// or:
$top = Top::first();
$articles = $top->articles()->orderBy('tops_has_posts.range', 'asc')->get();

Esto ordenará la consulta relacionada.

Nota: No te compliques la vida nombrando las cosas de esta manera. posts no son necesariamente articles , usaría uno u otro nombre, a menos que realmente sea necesario.