Yii2 Dynamic Relational, Eager loading

Yii2 Dynamic Relational Eager Loading

In Yii2, dynamic relational eager loading allows you to load related models dynamically and eagerly. This means that you can specify the related models to load at runtime and load them all at once, reducing the number of database queries.

To use dynamic relational eager loading in Yii2, you can use the with() method in your query. The with() method accepts an array of relation names or anonymous functions that define the relations to be loaded.

Here's an example of how to use dynamic relational eager loading in Yii2:

use yii\db\ActiveRecord;

class Post extends ActiveRecord
    public function getComments()
        return $this->hasMany(Comment::class, ['post_id' => 'id']);

class Comment extends ActiveRecord
    public function getUser()
        return $this->hasOne(User::class, ['id' => 'user_id']);

// Example usage
$posts = Post::find()

In the example above, we have two models: Post and Comment. The Post model has a one-to-many relation with the Comment model, and the Comment model has a one-to-one relation with the User model.

By using the with(['comments.user']) method, we can load the comments relation and the user relation for each comment in a single query. This reduces the number of queries executed and improves performance.

Please note that the example provided is a simplified version to demonstrate the concept of dynamic relational eager loading in Yii2. In a real-world scenario, you would need to define the appropriate relations in your models and adjust the code accordingly.