从 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'){
}
但我仍然找不到实际的记录。
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 want to get all the users which have full paid total amount of the
diploma invoice. - I want also get all the users which have not full paid total amount
of the diploma invoice.
I'm currently looping through the each relation.
$users = User::has('diplomas');
then foreach loop on users and get all invoices.
$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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题不同,你的代码也不同。
如果您想要关系数据,则可以使用“With”获取关系数据
如果你想要 less_paid | no_paid 那么您可以在关系模型函数中使用 where 语句。
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 | no_paid then you can use where statement in your relation model function .