skip to Main Content

I have one to many relations

Relations Picture

In my User Model

public function user_balances(){
    return $this->hasMany(UserBalances::class);
}

In my User Balances Model

public function user(){
    return $this->belongsTo(UserBalances::class);
}

So every time I want to retrieve the last record of user balance, I always do

$user = User::first();
$user->user_balances->last()

The issue is last() method order the records by created_at timestamp, and my user balances records is rapidly stored, so it has chance to have same timestamp. and when I want to retrieve the latest data it not synchronize.

can I override the last() method and order it by id instead of timestamp?

I have try using different way to retrieve last records by doing this

$user = User::first();
$user_balance_last = UserBalance::where('user_id', $user->id)->latest('id')->first();

2

Answers


  1. Define this in the relationship itself. For latest ones, define a new relationship because both all user balances and only latest balance would be required for building the application.

    public function user_balances_latest(){
        return $this->hasMany(UserBalances::class)->latest('id');
    }
    
    $user = User::first();
    dd($user->user_balances_latest)
    
    Login or Signup to reply.
  2. Try to create scope for the same query:

    public function scopeLastBalance($query)
    {
       return $query->user_balances()->latest('id')->first();
    }
    

    You can call it through:

    $user->LastBalance();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search