php - Laravel:如何从结果访问表主键

标签 php mysql laravel

Model: User
Primary Key: emp_no (alphanumeric)
Fields: password, remember_token

Model: Employee
Primary Key: emp_no (alphanumeric)
Fields: first_name, last_name

使用$users = Users::with('employee')->get();' 我可以获得用户列表及其各自的员工记录。

我可以迭代

@foreach($users as $user)
    {{ $user->emp_no}} //Not working, always returns 0
    {{ $user->password }} //Working
    {{ $user->remember_token }} //Working
    {{ $user->employee->emp_no}} //Not working, always returns 0
    {{ $user->employee->first_name }} //Working
    {{ $user->employee->last_name }} //Working
@endforeach

正如我所评论的,两者都尝试显示作为两个表的主键的 emp_no 不起作用。

最佳答案

缺少一些信息,我们在 Laravel 的 IRC channel 上聊了一会儿。问题是可能模型仍然有$incrementing = true并且他的主键是一个字符串。 $incrementing 属性需要设置为 false。

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

来源:https://laravel.com/docs/5.4/eloquent

关于php - Laravel:如何从结果访问表主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44173037/

相关文章:

MySQL 错误 key 文件不正确。 myisamchk 修复有效,但表很快再次损坏

javascript - Vue 和 Laravel 表单验证未返回 422 响应

mysql - 启动 mariadb 时出错 - 没有这样的过程

javascript - 如何在 laravel 中显示引导弹出模式?

php - 如何设置代码以在将行复制到表2后自动从表1中删除行

Mysql单表复杂问题

php - MAMP-Mac OS X

php - Laravel 4路由到 Controller 方法

php - 在 php 中的 Android post 请求

php - Codeigniter 项目中的条件大小写错误