php - 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');
}
我应该怎么办?谢谢。
解决方案
我找到了我的问题的解决方案。
我需要将此行添加到用户模型:
public $incrementing = false;
并将主键更改为名称:
protected $primaryKey = 'name';
仅供参考:这只是一个例子,我知道使用名称作为主键是不对的。我想我可以将它用于用户名或另一个唯一键(不增加一个)之类的东西。
谢谢。
参考:https ://github.com/Laravel-Backpack/CRUD/issues/179#issuecomment-486684173
推荐阅读
- javascript - 如何使用 HERE API 填充两个表单字段 - 一个带有坐标,一个带有地址?
- php - 如何通过 GET 请求将所有 PNG、JPG 和 JPEG 链接重定向到特定的 PHP 文件
- regex - RegEx 用于匹配数字和带量词的一个点
- oauth-2.0 - Keycloak 能否将 JWT 访问令牌中的范围作为数组包含在内?
- php - 仅将 where 条件应用于一次事件
- linux - BASH 脚本中的日历月份变量
- c# - 汽车发电机对象设计
- php - Unable to fetch data in view using laravel
- r - 我想创建一个柱形图,其中每列是两种特定颜色之一
- design-patterns - 从复杂的数据库功能构建复杂对象的良好设计模式是什么?