class PaymentMethod extends Model
{
....
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
...
}
class User extends Authenticatable
{
...
public function payment_methods()
{
return $this->hasMany(PaymentMethod::class, $this->getForeignKey())->orderBy('created_at', 'desc');
}
public function default_payment_method()
{
return $this->hasOne(PaymentMethod::class, 'id', 'default_payment_method_id');
}
...
}
在视图中
@if($user -> getDefautPaymentMethod()->type == PaymentMethod::PAYPAL_ACCOUNT)
<div><strong>Paypal: </strong> {{$user -> getDefautPaymentMethod()-> paypal_email}}</div>
@else
<div><strong>Card: </strong>{{$user -> getDefautPaymentMethod()-> card_brand}} **** **** **** {{$user -> getDefautPaymentMethod()-> card_last_four}}</div>
@endif
这项工作很好。并为用户输出默认付款方式。
但我不想为用户输出所有付款方式。并且对于每个方法输出标签,如果这是用户的默认值。
我不希望在cicle
中使用DB :: RAW或子查询 @foreach($user->payment_methods()->get() as $payment_method)
@if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)
<div><strong>Paypal: </strong> {{$payment_method -> paypal_email}}</div>
@else
<div><strong>Card: </strong>{{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}</div>
@endif
@endforeach
如果方法默认,如何影响此cicle和模型代码输出?
答案 0 :(得分:1)
您可以循环使用付款方式,并将ID与默认付款方式ID进行比较。他们可以匹配,你知道它是默认的。
@foreach ($user->payment-methods()->get() as $payment_method)
<div>
@if ($user->get_default_payment_method()->id === $payment_method->id)
<strong>Default Payment Method</strong>
@endif
{{ $payment_method }}
</div>
@endforeach
答案 1 :(得分:0)
我找到了解决方案:
{{1}}