Laravels Eloquent ORM:设置模型的数据类型 [英] Laravels Eloquent ORM: setting datatypes of the model

查看:503
本文介绍了Laravels Eloquent ORM:设置模型的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个简单的表,其中包含两行:idkey.

Currently I have a simple table with two rows: id and key.

每当我尝试使用City::get()从数据库中获取数据时,响应都将包含字符串格式的id列.

Whenever I try to get my data from the database with City::get() the response contains id columns in the string format.

有没有一种简单的方法/程序包,可以为每个列定义数据格式?例如. -在此示例中,id应该是整数.

Is there a simple way/package how I can define the data formats for each of my columns? E.g. - id in this example should have been an integer.

型号:

<?php
class City extends Eloquent {

    protected $table = 'cities';
    protected $primaryKey = 'Id';

}

控制器:

Controller:

class CityController extends \BaseController {

    public function index()
    {
        var_export(is_integer(City::get()->first()->Id));
        var_export(is_string(City::get()->first()->Id));
        die;
    }

}

输出:

false
true

推荐答案

来自数据库的记录中的每个字段都将是一个字符串.

Every field from a record that comes out of the database is going to be a string.

这似乎是PHP中有多少个数据库扩展名可以使用的功能.

This is just how many db extensions in PHP seem to work.

Ruby on Rails保持模式的恒定映射,以知道tableA.field1是整数,因此在获取数据库时,它可以将任何内容转换为int.这显然有一些开销,但是它可能是一个有用的功能. Laravel选择不这样做是为了性能而不是方便.

Ruby on Rails keeps a constant map of the schema to know that tableA.field1 is an integer, so it can convert anything to an int when it fetches the database. This obviously has some overhead to it, but it can be a useful feature. Laravel opted to not do this in the interest of performance over convenience.

您可以使用访问器和变异器手动复制此功能.

You can use accessors and mutators to manually replicate this functionality.

这篇关于Laravels Eloquent ORM:设置模型的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆