【问题标题】:BackPack for Laravel: Display two fields with same nameBackPack for Laravel:显示两个同名字段
【发布时间】:2019-06-13 10:01:16
【问题描述】:

我有什么:

数据库中的表:

Schema::create('orders', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('primary_person');
    $table->unsignedBigInteger('secondary_person');
});
Schema::create('persons', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('first_name', 255);
    $table->string('last_name', 255);
});

型号:

class Order extends Model
{
    use CrudTrait;

    protected $table = 'orders';
    protected $fillable = [
        'primary_person',
        'secondary_person',
    ];

    public function primaryPerson()
    {
        return $this->hasOne(Person::class, 'id', 'primary_person');
    }

    public function secondaryPerson()
    {
        return $this->hasOne(Person::class, 'id', 'secondary_person');
    }
}

需要做什么:

在页面编辑订单我想显示两个人的信息:

  • 主要人员的名字
  • 主要人员的姓氏
  • 次要人员的名字
  • 第二个人的姓氏

我做了什么:

在 OrderCrudController.php 中添加:

$this->crud->addFields([
    [
       'label' => 'First Name of Primary person',
       'type' => 'text',
       'name' => 'first_name',
       'entity' => 'primaryPerson',
       'model' => 'App\Models\Person',
    ],
    [
        'label' => 'Last Name of Primary person',
        'type' => 'text',
        'name' => 'last_name',
        'entity' => 'primaryPerson',
        'model' => 'App\Models\Person',
    ],
    [
        'label' => 'First Name of Secondary person',
        'type' => 'text',
        'name' => 'first_name',
        'entity' => 'secondaryPerson',
        'model' => 'App\Models\Person',
    ],
    [
        'label' => 'Last Name of Secondary person',
        'type' => 'text',
        'name' => 'last_name',
        'entity' => 'secondaryPerson',
        'model' => 'App\Models\Person',
    ]
]);

我收到了什么:

只有最新的两个字段(第二个人信息)。

我想看什么

主要问题:

我无法显示具有相同 "name" 的字段,因为 "name" - 属性(数据库中的列),它也将成为名称输入。
在列中,这种情况使用 "key" 属性处理。 但在 Fields 中它不起作用。

【问题讨论】:

    标签: php laravel crud laravel-backpack


    【解决方案1】:

    可能的解决方案——使用访问器和修改器(非常感谢@tabacitu)。
    https://dev.to/sergunik/how-to-display-two-fields-with-same-name-in-backpack-for-laravel-8b1

    【讨论】:

      【解决方案2】:

      确实,您不能有两个具有相同名称的字段。在列中可以使用 key 属性,但正如您所提到的,在创建/更新表单中,由于 HTML 表单的工作方式,这是一个问题:只有最后一个输入的值将传递给 PHP,存储在数据库。

      我建议您使用accessors & mutators 解决此问题。您可以将第二个字段命名为其他名称,即使该列在数据库中不存在。然后只需在你的模型中使用一个```setSecondFirstName($value)```` 方法来获取该值并根据需要保存它。

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2020-02-02
        • 2021-08-30
        • 2011-02-08
        • 2017-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多