首页 > 解决方案 > Laravel:如何存储在下拉字段中显示和选择的值作为输入,而不是 id

问题描述

我使用 Laravel 4.1 的背包。

表:用户

---------------------------
| id |        name        |
---------------------------
| 1  | Rory Choi          |
---------------------------
| 2  | Freddie Farrington |
---------------------------
| 3  | Cristian Wyatt     |
---------------------------

表:文件

我希望存储在表中的值是用户表中名称的值,而不是 id。

我想要这个

-------------------------------------------------------
| id |     description     |           name           |
-------------------------------------------------------
| 1  | Something           | Cristian Wyatt           |
-------------------------------------------------------
| 2  | Other thing         | Freddie Farrington       |
-------------------------------------------------------
|    |                     |                          |
-------------------------------------------------------

不是这个

-------------------------------------------------------
| id |     description     |           name           |
-------------------------------------------------------
| 1  | Something           | 3                        |
-------------------------------------------------------
| 2  | Other thing         | 2                        |
-------------------------------------------------------
|    |                     |                          |
-------------------------------------------------------

文档控制器 .php:

它确实显示了用户表中的名称列表,但它不存储名称值

protected function setupCreateOperation()
{
    CRUD::addField([
        'label'     => 'Username',
        'name'      => 'username',
        'type'      => 'select2',
        'entity'    => 'users', // the method that defines the relationship in your Model
        'attribute' => 'name', // foreign key attribute that is shown to user
    ]);
}

文件.php

定义关系的方法。

public function users()
{
    return $this->hasOne('User','name','name');
}

我应该怎么办?谢谢。

标签: phplaravellaravel-7laravel-backpack

解决方案


我找到了我的问题的解决方案。

我需要将此行添加到用户模型:

public $incrementing = false;

并将主键更改为名称:

protected $primaryKey = 'name';

仅供参考:这只是一个例子,我知道使用名称作为主键是不对的。我想我可以将它用于用户名或另一个唯一键(不增加一个)之类的东西。

谢谢。

参考:https ://github.com/Laravel-Backpack/CRUD/issues/179#issuecomment-486684173


推荐阅读