Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make MySQL driver for HHVM return IDs as integers?

I noticed that my Laravel API does not return entity identifiers (the primary keys) as integers.

In Api\PostController.php::show():

function index()
{
    $posts = Post::all();

    return $posts;
}

Which returns something like:

[{
    "id": "1",
    "title": "Post one",
    ...
},{
    "id": "2",
    "title": "Post two",
    ...
}]

This messes up my table sorting (because IDs will be sorted as string: 1, 10, 11, 2 etc.).

Dumping the entity itselfs also shows that the id attribute is a string.

As mentioned here the probable cause is that the MySQL driver does not return values in the appropriate type.

I'm using HHVM 3.3.1 on a Ubuntu 14.04 server. Is there any way I can use a native MySQL library (like php5-mysqlnd) for HHVM?

I could use Laravel model accessors to solve the problem. But that is more of a hack IMO.

Please help!


References:

  • http://forumsarchive.laravel.io/viewtopic.php?pid=58151
  • https://github.com/facebook/hhvm/issues/3619

EDIT: I have verified that it's not the ORM layer of Laravel. The PDO instance already returns IDs as strings.

like image 249
mauvm Avatar asked Nov 07 '14 13:11

mauvm


2 Answers

Create an accessor for the id in your Post class.

class Post extends Eloquent {

    public function getIdAttribute($value)
    {
        return (int)$value;
    }

}
like image 92
slapyo Avatar answered Nov 19 '22 23:11

slapyo


You need to set typed_results in your /etc/hhvm/php.ini file.

hhvm.mysql.typed_results = true

like image 1
Ian Chadwick Avatar answered Nov 19 '22 23:11

Ian Chadwick