db icon indicating copy to clipboard operation
db copied to clipboard

Query::one() should return null instead of false, when no results

Open brandonkelly opened this issue 8 years ago • 3 comments

yii\db\Query::one() returns false if there are no results. In a rare break from consistency, yii\db\ActiveQuery::one() returns null instead.

I can’t think of any reason why they would need to return different things, so this is probably just an oversight.

Of the two, null is probably the better option, as it’s more semantic and would allow the result could be used in conjunction with a ?? operator, e.g

$foo = $query->one() ?? 'default';

So Query::one() is the method that should change.

brandonkelly avatar Nov 13 '17 17:11 brandonkelly

I don't remember the reason why it was made like that initially and I think that fixing it in 2.0 may cause issues in existing apps. Should be fixed in 2.1 for sure.

samdark avatar Nov 13 '17 17:11 samdark

Agree, should be fixed in 2.1, not 2.0.x

brandonkelly avatar Nov 13 '17 18:11 brandonkelly

This is PDO behavior, we simply pass through the result we obtain from PDO. Command::queryOne() returns array|false and so does Query::one(). ActiveQuery returns objects so we change it to null on that layer because null fits better in object context.

We already had this discussion, so this is a duplicate of https://github.com/yiisoft/yii2/issues/8677

Imo its not necessary to add an extra check for all places where we call PDO and change the return type. ?? however is a good argument. Closing #8677 as this issue comes with more arguments than just inconsitency.

cebe avatar Nov 13 '17 19:11 cebe

done.

terabytesoftw avatar Feb 18 '23 18:02 terabytesoftw