Home > OS >  Laravel eloquent and eager loading
Laravel eloquent and eager loading

Time:08-15

*transaction Table

 id   invoice_no
 3     arm0003
 4     arm0004
 8     arm0008

*debt_payment Table

id      transaction_id      parent_id
1               8               3
2               8               4

*Transaction Model

  public function debtPayment()
    {
        return $this->hasMany(DebtPayment::class, 'transaction_id');
    }

#My expected output was:

Transaction_data_array: [▼
  "id" => 8
  "invoice_no" => 'arm0008'
  "debt_payment" => array:1 [▼
      0 => array:4 [▼
        "id" => 1
        "transaction_id" => 8
        "parent_id" => 3
        "transaction" => array:2 [▼
            "id" => 3
            "invoice_no" => 'arm0003'
          ]
      ],
      1 => array:4 [▼
        "id" => 2
        "transaction_id" => 8
        "parent_id" => 4
        "transaction" => array:2 [▼
            "id" => 4
            "invoice_no" => 'arm0004'
          ]
      ]
  ]
]

I have no idea for this result. This is my failure query.

  $id = 8;
  $transaction = Transaction::where('id',$id)
                    ->with('debtPayment')
                    ->whereHas('debtPayment', function ($query) use($id){
                        $query->select('*')
                            ->from('transactions')
                            ->whereIn('id', function($query) use($id){
                                $query->select('parent_id')
                                    ->from('debt_payments')
                                    ->where('transaction_id', $id)
                                    ->pluck('parent_id');
                            })
                            ->get();
                    })
                    ->first();

How can I get my expected output using laravel eloquent query. Somebody help me!

CodePudding user response:

You can try this :
In DebtPayment model:

public function transaction()
{
   return $this->belongsTo(Transaction::class, 'parent_id');
}
$id = 8;
$transaction = Transaction::with('debtPayment.transaction')
               ->where('id', $id)
               ->first()
               ->toArray();
  • Related