I have 2 tables with 1->many relation. such as:
- Account.php (account model)
// has many ledgers
public function ledger()
{
return $this->hasMany('Model_path\Ledger', 'account_id', 'id');
}
- Ledger.php (ledger model)
public function ledger()
{
return $this->belongsTo('Model_path\Account', 'account_id', 'id');
}
I want to get latest ledger entry that is linked with an Account. I did this.
$query = Account::select(
[
'id', 'name', 'type', 'address', 'contact', 'email', 'status'
]
)->where('type', 'personal')->with([
'ledger' => function ($q) {
$q->select([
'id', 'date_ad', 'date_bs', 'narration', 'debit_amount', 'credit_amount', 'balance', 'remarks', 'account_id', 'created_at'
])->orderBy('created_at', 'desc')->take(1);
}
])->get();
This returns exactly what i want. But only when the Ledger table have more then 1 row linked with an Account.
In case, of where there is only 1 row linked in ledger table. This returns empty array. I expect it returns that 1 row from Ledger Table that is linked with the Account.
I have tried
->latest();
->first();
->limit(1);
All of these gives same result.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire