gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:55:17 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com