[英]fetch record from with dependent relations in laravel
我有下表。
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
我目前正在遍历每个关系。
$users = User::has('diplomas');
然后对用户进行 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'){
}
但我仍然无法找到实际记录。
您的问题不同,您的代码也不同。
如果你想要关系数据,那么你可以使用“With”获取关系数据,如果你想要 less_paid | no_paid 那么你可以在你的关系 model function 中使用 where 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.