php 获取 Eloquent 模型实例的主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30457184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get primary key of Eloquent model instance
提问by Basaa
I'm happy enough to work on a project with (not) very consistent column names in our MySQL database. We have camelCase, PascalCase, 'Id', ID and it's driving me nuts. I've decided to start using Eloquent in our application (which is NOT Laravel). I would love to have a method of receiving the value of the primary key easily without knowing the column name e.g.
我很高兴能够在我们的 MySQL 数据库中使用(不是)非常一致的列名进行项目。我们有camelCase、PascalCase、'Id'、ID,这让我很抓狂。我决定开始在我们的应用程序(不是 Laravel)中使用 Eloquent。我希望有一种方法可以在不知道列名的情况下轻松接收主键的值,例如
// User's primary key column is called UserID
$user = User::find(1337);
$userId = $user->id(); // = 1337
Is there a Eloquent way of doing this or am I gonna have to add this method myself?
有没有 Eloquent 的方法来做到这一点,还是我必须自己添加这个方法?
回答by Mark Baker
You should have define a protected field in your model telling Eloquent what the primary key column is:
您应该在模型中定义一个受保护的字段,告诉 Eloquent 主键列是什么:
protected $primaryKey = 'guid';
Then you can access that property in your model
然后您可以在模型中访问该属性
The model's getKey()
method should give you value of the primary key, while getKeyName()
should tell you what column name is used for the primary key
模型的getKey()
方法应该给你主键的值,同时getKeyName()
应该告诉你主键使用什么列名