简体   繁体   中英

Laravel eager load model relation using model instance?

Is there any other way to eager load the modal relation and avoid having ['invoicePayments'] array selector?

fx:

$payment->load(['invoice.source', 'invoice.user'])
            ->getRelations()['invoicePayments'];

The main reason is like this for now is because I am using model binding injection, so my method is just function getInvoicePayments(Payment $payment) but I feel this array selection is wrong, but I can't think in any other solution for it? any ideas?

All of the following should be equivalent:

$one = $payment->load(['invoice.source', 'invoice.user'])->getRelations()['invoicePayments'];

$two = $payment->load(['invoice.source', 'invoice.user'])->getRelation('invoicePayments');

$thr = $payment->load(['invoice.source', 'invoice.user'])->invoicePayments;

dd($one, $two, $thr);

You can also manually try to access every relationship's property, this will force Laravel to load the relationship in the model's instance:

$payment->invoice->source;
$payment->invoice->user;
$payment->invoicePayments;

I actually don't like doing this, but it's another working way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM