我正在使用Laravel 7 + Backpack CRUD 4.1。
我有两个模型Payment
和PaymentMethods
,并且在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');
}
但是我仍然在选择选项中看到所有记录。如何过滤选择的值?
答案 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');
}
第二个参数应该是外键...