I have one to many relations
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
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.Try to create scope for the same query:
You can call it through: