[英]fetch record from with dependent relations in laravel
I have the following tables.我有下表。
users -> id, name, email, password
diplomas -> id, name
user_diploma -> user_id, diploma_id
invoices -> id, user_id, total_amount
invoice_items -> id, item_id, item_type // items can be diplomas or any other models also.
payments -> id, invoice_id, paid_amount
I'm currently looping through the each relation.我目前正在遍历每个关系。
$users = User::has('diplomas');
then foreach loop on users and get all invoices.然后对用户进行 foreach 循环并获取所有发票。
$users = User::has('diplomas');
if($this->paymentStatus == 'full_paid'){
foreach ($users as $user) {
$diplomas = $user->diplomas->pluck('id')->toArray();
$invoices = $user->invoices()
->whereHas('items', function ($q) use ($diplomas) {
$q->whereItemType(\App\Models\Diploma::class);
$q->whereIn('item_id', $diplomas);
})
->whereHas('payments', function ($q){
// still don't know how to fetch the invoice id here to compare the total paid amount
})->get();
$allInvoices = $allInvoices->merge($invoices);
}
}
else if($this->paymentStatus == 'less_paid'){
}
else if($this->paymentStatus == 'no_paid'){
}
But I'm still unable to find actual records.但我仍然无法找到实际记录。
your question is different and your code is different.您的问题不同,您的代码也不同。
if you want relation data then you can fetch relation data using "With" and if you want less_paid |如果你想要关系数据,那么你可以使用“With”获取关系数据,如果你想要 less_paid | no_paid then you can use where statement in your relation model function.
no_paid 那么你可以在你的关系 model function 中使用 where 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.