lundi 17 janvier 2022

Get latest item in OneTomany relationship laravel 5.5

:)

I've a problem with a relationship in my project, this is the situation, I have two models "Sucursales" and "Checklist", this is the logic... one sucursal can have many checklist, but is one request I only need to get the most recent sucursal's checklist... the simple relation works fine when I call it, but when I'm trying to get the most recent checklist the result is empty, here is the code:

Sucursales Model

class Sucursales extends Model
{
    protected $table = 'db_sucursales';
    protected $primaryKey = 'id_sucursal';
    protected $fillable =['tipo_sucursal', 'no_sucursal', 'id_gcb', 'id_coordinacion', 'nombre_sucursal', 'id_estado', 'direccion_sucursal', 'telefono_sucursal', 'id_estatus'];
    public $timestamps = false;

    public function checkslist(){
        return $this->hasMany(ChecklistSucursal::class, 'id_sucursal','id_sucursal');
    }
}

Checklist model:

class ChecklistSucursal extends Model
{
    protected $table = 'db_checklist_sucursales';
    protected $primaryKey = 'id_checklist';
    protected $fillable = [
        'folio', 'id_sucursal', 'id_usuario', 'nombre_aplicador', 'encargado_sucursal', 'puesto_encargado_sucursal', 'fecha_aplicacion', 'checklist','estatus','comentarios'
    ];

    public function sucursal(){
        return $this->hasOne(Sucursales::class, 'id_sucursal', 'id_sucursal');
    }
    
}

When I call:

$sucursales = Sucursales::with('checkslist')->orderBy('no_sucursal', 'asc')->get();

works fine, but when I call the next code:

$sucursales = Sucursales::with(['checkslist' => function($query){
                return $query->latest('fecha_aplicacion');
            }])
                            ->orderBy('no_sucursal', 'asc')
                            ->get();

the result is empty...

Please someone can tell me what I'm doing wrong, this project is in laravel 5.5



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire