Yii2 Dynamic Relational Query

To perform dynamic relational queries in Yii2, you can use the ActiveQuery class provided by the framework. This class allows you to build queries that involve multiple related models.

To start, you need to define the relationships between your models using the appropriate methods in your ActiveRecord classes. These methods include hasOne(), hasMany(), belongsTo(), and hasManyThrough(), among others.

Once the relationships are defined, you can use the with() method in your query to specify the related models that you want to fetch. This will enable you to retrieve the related data in a single query, avoiding the need for additional queries to fetch the related data.

Here's an example of how you can perform a dynamic relational query using 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 getPost()
    {
        return $this->hasOne(Post::class, ['id' => 'post_id']);
    }
}

To fetch the posts along with their comments, you can use the following code:

$posts = Post::find()
    ->with('comments')
    ->all();

In this example, the with('comments') method specifies that you want to fetch the comments related to each post. The all() method executes the query and retrieves all the posts along with their comments.

You can also perform additional filtering, sorting, and pagination on the related data by chaining additional methods to the query.

This is a basic example of how you can perform dynamic relational queries in Yii2. By defining the appropriate relationships and using the with() method, you can efficiently fetch related data in a single query.