简体   繁体   English

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

[英]Laravel: How to access the table primary key from result

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

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

Using $users = Users::with('employee')->get();' 使用$users = Users::with('employee')->get();' I could get the list of users with their respective employee record. 我可以获取用户列表以及他们各自的员工记录。

I can iterate by 我可以反复

@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

As I commented, both attempt to display the emp_no which is the primary key for both table doesn't work. 正如我所评论的,这两种尝试都显示emp_no,这是两个表的主键都行不通。

There's some information lacking, and we chatted for a short while on Laravel's IRC channel. 缺少一些信息,我们在Laravel的IRC频道上聊了一会儿。 The issue is probably that the model still has $incrementing = true and his primary key is a string. 问题可能是该模型仍然具有$incrementing = true且其主键是字符串。 The $incrementing property needs to be set to false. $ 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. 此外,Eloquent假定主键是一个递增的整数值,这意味着默认情况下,主键将自动转换为int值。 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. 如果希望使用非增量或非数字主键,则必须将模型上的公共$ incrementing属性设置为false。

Source: https://laravel.com/docs/5.4/eloquent 资料来源: https : //laravel.com/docs/5.4/eloquent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM