筛选选择字段中的值

时间:2020-07-26 18:16:09

标签: laravel backpack-for-laravel laravel-backpack

我正在使用Laravel 7 + Backpack CRUD 4.1。

我有两个模型PaymentPaymentMethods,并且在PaymentCrudController中有字段

$this->crud->addField([
   'label'     => 'Payment Method',
   'type'      => 'select2',
   'name'      => 'payment_method_id',
   'entity'    => 'paymentMethod',
   'attribute' => 'name',
   'model'     => 'App\Models\PaymentMethod',
   'wrapperAttributes' => [
       'class' => 'form-group col-md-3',
   ],
]);

Payment模型中的关系:

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

实际上,这可以按预期工作-我在选项字段中看到了PaymentMethod模型中的所有记录。但是我需要过滤一些值。我试图修改模型关系:

 public function paymentMethod()
        {
            return $this->hasOne(PaymentMethod::class, 'id', 'payment_method_id')->where('name', '!=', 'Online');
        }

但是我仍然在选择选项中看到所有记录。如何过滤选择的值?

1 个答案:

答案 0 :(得分:1)

将“哪里”放在关系中是没有意义的,在我看来,关系应该保持原样,反映表的关系...。

为适合您,可以在“ select2”字段中使用“ options”:

  $this->crud->addField([
       'label'     => 'Payment Method',
       'type'      => 'select2',
       'name'      => 'payment_method_id',
       'entity'    => 'paymentMethod',
       'attribute' => 'name',
       'model'     => 'App\Models\PaymentMethod',
       'options' => (function ($query) {
        return $query->where('name', '!=', 'Online')->get();}),
       'wrapperAttributes' => [
           'class' => 'form-group col-md-3',
       ],
    ]);

您的one to many relation的其他东西:应该是

public function paymentMethod()
    {
        return $this->hasOne(PaymentMethod::class,'payment_method_id');
    }

第二个参数应该是外键...