cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Mvc\Collection findById not working

Open emrecdr opened this issue 13 years ago • 3 comments

I have a record on my mongo db user table: { "_id": "abc", "email": "[email protected]", "fullname": "First Test User", "gender": "male" }

When I tried to get record via findFirst, I am getting correct result:

$user = User::findFirst(array(array("_id" => 'abc'))); var_dump($user);

output: object(User)[78] public '_id' => string 'abc' (length=3) public 'email' => string '[email protected]' (length=12) public 'fullname' => string 'First Test User' (length=15) public 'gender' => string 'male' (length=4) ...

But when I tried to get record via findById, I am getting false:

$user = User::findById('abc'); var_dump($user);

output: boolean false

I have also tried: $user = new User(); $user->findById('abc');

but it also returned false.

Am I doing something wrong?

emrecdr avatar Jan 18 '13 01:01 emrecdr

Maybe the 'abc' isn't matching the string of 24 characters expected by MongoId (http://php.net/manual/en/class.mongoid.php) and for that reason it isn't returning any document.

ghost avatar Jan 18 '13 05:01 ghost

Your primary key _id is a string. findById('abc') automatically converts 'abc' to MongoId('abc'). As such, the following two are different:

db.user.findOne({_id: ObjectId('abc')}); db.user.findOne({_id: 'abc'});

Considering that the only requirement for a primary key is that it should be unique, findById should probably take a second argument that could be a boolean and defaults to true. If the value of the argument is true, the _id is passed a MongoId object. Otherwise, the primary key value should be whatever type is passed.

lobostome avatar Jan 18 '13 21:01 lobostome

From 0.9.0 you can disable the implicit MongoIds with:

class Robots extends Phalcon\Mvc\Collection
{
    public function initialize()
    {
           $this->useImplicitObjectIds(false);
    }
}

ghost avatar Jan 21 '13 08:01 ghost