简体   繁体   English

有条件的 MorphTo

[英]MorphTo with conditions

I am working with field MorphTo and I try to make conditions for the resources.我正在使用 field MorphTo并尝试为资源创造条件。

For example I have 4 resources:例如我有 4 个资源:

Accounts帐户

PaymentMethodCreditCard付款方式信用卡

PaymentMethodBankAccount支付方式银行账户

Transactions交易

Every Account can add as many Payment Methods as he wants.每个帐户都可以根据需要添加任意数量的付款方式。 And in the transaction I work with MorphTo to select the Payment Method that the account selected.在交易中,我使用MorphTo select 帐户选择的付款方式。

My problem starts when I try to create a transaction from Nova and get a list of all the Payment Methods in the db without any relation to the account.当我尝试从 Nova 创建交易并获取数据库中与帐户无关的所有付款方式的列表时,我的问题就开始了。

My ideal idea was like that:我的理想想法是这样的:

        MorphTo::make('Transactions')
        ->withoutTrashed()
        ->dependsOn('Account', function (MorphTo $field, NovaRequest $request, FormData $formData) {
            if(isset($formData->Account)){
                $field->types([
                    PaymentMethodCreditCard::class => fn($q)=>$q->where('account_id', $formData->Account),
                    PaymentMethodBankAccount::class => fn($q)=>$q->where('account_id', $formData->Account),
                ]);
            }
        }),

But of course it will not work, Someone has any idea how I can add conditions to the resource?但它当然不会起作用,有人知道我如何向资源添加条件吗?

I'll give you two answers.我给你两个答案。 Since the question does not exactly clarify whether the Account value is changable during the edit process or it's predefined.由于该问题并未明确说明 Account 值在编辑过程中是可变的还是预定义的。

Account value does not change.账户价值不变。

If the account value does not change after the resource is loaded, then the solution you are looking for is Relatable Filtering如果加载资源后账户值没有变化,那么你要找的解决方案是Relatable Filtering

public static function relatablePaymentMethods(NovaRequest $request, $query)
{
    $resource = $request->findResourceOrFail();
    return $query->where('account_id', $resource->Account);
}

Account value can change账户价值可以改变

If the account value can change, then you'll need to create your own "Morph To" behavior using Select and Hidden fields.如果帐户值可以更改,则您需要使用Select隐藏字段创建自己的“变形为”行为。

With Select field, you can utilize the dependsOn and options functions, to change the query results when the Account changes.有了 Select 字段,可以利用 dependsOn 和 options 函数,在 Account 发生变化时改变查询结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM