doujinyi1267 2017-10-27 00:31
浏览 97
已采纳

为什么要改变Eloquent ORM的价值?

I face small puzzle problem in Laravel select query. It automatic change data type.

When i use

$data = Model::select('user_id AS id')->get(); 

data is [{"id":3},{"id":4}] // not actual value

But When i use (only change Alias id to ID)

$data = Model::select('user_id AS ID')->get(); 

data is [{"ID":"03"},{"ID":"04"}] // actual value

what is the problem

  • 写回答

1条回答 默认 最新

  • doubei5310 2017-10-27 02:38
    关注

    This is because Laravel automatically casts the id field to an integer, as it will be the primary key of your model.

    Primary Keys

    Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

    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. If your primary key is not an integer, you should set the protected $keyType property on your model to string.

    laravel.com/docs/5.5/eloquent

    If you wish to set the property ID to an integer, you can use Eloquent's Attribute Casting:

    laravel.com/docs/5.5/eloquent-mutators#attribute-casting

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部