gpt4 book ai didi

php - Blade 中的 Laravel 5.5 Eloquent 请求和许多 sql 查询

转载 作者:行者123 更新时间:2023-11-29 10:31:29 24 4
gpt4 key购买 nike

我需要输出用户付款历史记录。附有付款方式详情。例如每次付款的卡或 Paypal 数据

<table border="1">
<tr>
<th>
</th>
<th>
summ
</th>
<th>
date
</th>
<th>
payment method
</th>
<th>
subscription
</th>
<th></th>
</tr>
@foreach($user -> payments()->get() as $payment)
<tr>
<td>
{{$payment->type}}
</td>
<td>
{{$payment->amount}}$
</td>
<td>
{{$payment->created_at}}
</td>
<td>
@if($payment -> payment_method()->first()->type == PaymentMethod::PAYPAL_ACCOUNT)
<div><strong>Paypal: </strong> {{ $payment -> payment_method() -> first() -> paypal_email }}</div>
@else
<div><strong>Card: </strong>{{ $payment -> payment_method() -> first() -> card_brand }} **** **** **** {{ $payment -> payment_method() -> first() -> card_last_four }}</div>
@endif
</td>
<td>
<div><strong>plan:</strong> {{ $payment->subscription->plan->name }}</div>
<div><strong>period:</strong> {{ $payment->period_start->format('d.m.Y')}} - {{ $payment->period_end->format('d.m.Y') }}</div>
</td>
<td>
@if (!empty($payment -> void_at))
<div>void {{ $payment -> void_at }}</div>
@elseif (!empty($payment->refund_at))
<div>refunded {{ $payment->refund_at }} </div>
@elseif(!empty($payment->refunded_transaction_id ))
<div>refund</div>
@endif
</td>
</tr>
@endforeach
</table>

此代码在每个循环迭代中生成许多 sql 请求:

select * from `payment_method` where `payment_method`.`id` = '3' and `payment_method`.`deleted_at` is null limit 1

select * from `payment_method` where `payment_method`.`id` = '3' and `payment_method`.`deleted_at` is null limit 1

我的模型:

用户类别。一对多支付关系

class User extends Authenticatable
{

public function payments()
{
return $this->hasMany(Payment::class, $this->getForeignKey())->orderBy('created_at', 'desc');
}

}

支付类别与支付方式一一对应

class Payment extends Model
{

public function payment_method()
{
return $this->belongsTo(PaymentMethod::class, 'payment_method_id', 'id');
}

如何更改我的代码以避免这种情况

最佳答案

你可以这样尝试:

$user = User::with("payments")->find($user_id);

并使用foreach

@foreach($user->payments as $payment)
{{$payment->type}}
@endforeach

当然,您可以根据需要更改这段代码。

关于php - Blade 中的 Laravel 5.5 Eloquent 请求和许多 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47345415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com