mercredi 30 mars 2016

Relationship order in laravel 5

I am having trouble with orderBy in laravel 5, using mysql datbase. Consider the following table structure:

calendarios

id (int) | descricao (varchar) | ano (int)

4 | 'Teste' | 2016

and eventos

id (int) | descricao (varchar) | data (date) | calendario_id (int)

1 | 'Festa' | '2016-05-13' | 4

2 | 'Natal' | '2016-12-25' | 4

Then, the respective models in my laravel project. Inside my 'Calendario' model, i have the following relationship:

/**
 * 
 * @return type
 */
public function eventos(){
    return $this->hasMany(\App\Cms\Evento::class);
}

But, when i try to get the "eventos" from "calendario" and order by date, it returns in the inverse order. For example:

$calendario = \App\Cms\Calendario::findOrfail(4);
if($calendario->eventos){

    foreach($calendario->eventos()->orderBy('data', 'desc')->get() as $evento){
        echo $evento->descricao . ' - ' . Carbon::parse($evento->data)->format('d/m');
    }

}

It is showing the event with the event 'Festa - 13/05' when the intended result would be display 'Natal 25/12' first. I'm stuck with this problem for hours... Is there something I'm missing?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire