laravel - 筛选选择字段中的值
问题描述
我正在使用 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');
}
但我仍然在选择选项中看到所有记录。如何过滤选择值?
解决方案
在我看来,将“位置”放在关系中没有任何意义,关系应该保持原样,反映表的关系....
对于您的适合,您可以使用“选项”作为“选择 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');
}
第二个参数应该是外键...
推荐阅读
- swift - 缺少标签栏。当我在 swift.for sidemenu 中打开 sidemenu 项目时,我正在使用 Drawercontroller
- javascript - 使用 websocket 执行 js 函数并等待返回值给 python 代码,反之亦然
- python - Pyspark 和 Python - 列不可迭代
- azure - 在 HTTP 连接器设置 LogicApps 中允许分块后仍然出现最大缓冲区大小错误
- html - 如何使我的标题背景颜色更小,同时保持响应
- python-3.x - 无法通过 Python 在 s3 存储桶上加载压缩的 csv 文件
- url - URL 格式:可以在 '?' 之前包含 '&' 在网址中?
- swift - 在 Swift 中裁剪肖像照片
- wordpress - 配置分页,以便从第二页开始使用不同的 Wordpress 模板
- sql-server - SQL Server:将实时数据从视图复制到表