jeudi 5 mars 2020

Laravel Eloquent: How to get only last row from linked table using with() function?

I have 2 tables with 1->many relation. such as:

  1. Account.php (account model)
    // has many ledgers
    public function ledger()
    {
        return $this->hasMany('Model_path\Ledger', 'account_id', 'id');
    }
  1. 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

1 commentaire:

  1. As reported by Stanford Medical, It's indeed the one and ONLY reason this country's women get to live 10 years longer and weigh an average of 42 lbs lighter than we do.

    (And realistically, it has absolutely NOTHING to do with genetics or some hard exercise and EVERYTHING around "how" they eat.)

    P.S, I said "HOW", not "what"...

    Click this link to uncover if this brief questionnaire can help you release your real weight loss potential

    RépondreSupprimer