首页 > 解决方案 > 筛选选择字段中的值

问题描述

我正在使用 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');
        }

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

标签: laravellaravel-backpack

解决方案


在我看来,将“位置”放在关系中没有任何意义,关系应该保持原样,反映表的关系....

对于您的适合,您可以使用“选项”作为“选择 2”字段:

  $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',
       ],
    ]);

别的东西......对于你的一对多关系:它应该是:

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

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


推荐阅读