#21077·yii2

ActiveRecord relation access on new model executes unnecessary query with 0=1 condition

Author: dmzryzCreated Aug 26, 2026Updated Aug 26, 2026
Labelstype:bug

Description

What steps will reproduce the problem?

Given an ActiveRecord model with a hasMany relation:

class User extends ActiveRecord
{
    public function getPosts()
    {
        return $this->hasMany(Post::class, ['id_user' => 'id']);
    }
}

Accessing the relation on a newly created model:

$user = new User();
$posts = $user->posts;

executes a database query:

SELECT * FROM [posts] WHERE (0=1)

What is the expected result?

No database query should be executed. Since $user is a new ActiveRecord instance and its primary key (id) is not set, the hasMany relation cannot possibly return any related records.

I would expect:

$user = new User();
$posts = $user->posts;
$posts === []

without executing a SQL query.

The query correctly returns no rows, but the database round trip is unnecessary.

Package version

2.0.55

PHP version

8.3.33