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