dsfsfsfsfs55656 2015-05-26 11:25
浏览 465
已采纳

获取Eloquent模型实例的主键

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.

// 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?

  • 写回答

1条回答 默认 最新

  • douchuang8359 2015-05-26 11:30
    关注

    You should have define a protected field in your model telling Eloquent what the primary key column is:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题