Simple method of joining tables in Yii2

Example 1: get Post model with joined Author model

Before joining "Author" you have to add relation to Post model like this:

    
        class Post extends ActiveRecord
        {
            //...

            public function getAuthor()
            {
                return $this->hasOne(Author::class, ['id' => 'author_id']);
            }
        }
    
    
        //get Post model with id - 5 and with joined Author model
        $id = 5;
        $post = Post::find()
            ->joinWith('author')
            ->where(['post.id' => $id])
            ->one();
        $author = $post->author->name; // get related Author model "name" property
    

Example 2: By using Query Builder (you dont need anything like adding relation methods)

    
        //get Post model with id - 5 and with joined Author model
        $id = 5;
        $query = new Query();
        $query->select(['post.*', 'author.name AS author_name'])->from('post');
        $query->innerJoin('author', 'author.id = post.author_id');
        $query->where(['post.id' => $id]);
        $post = $query->one();
        var_dump($post);

        //output
        array (size=7)
            'id' => string '5' (length=1)
            'author_id' => string '23' (length=2)
            'title' => string 'Hello world' (length=11)
            'text' => string 'My first post' (length=13)
            'author_name' => string 'Tom' (length=3)