如何在Yii2中只获得1个连接查询的多活动记录模型?

For example:

Query

 SELECT book.\*,author.* FROM book 
 INNER JOIN author ON author.id = book.author_id 
 WHERE book.id=1

Get model

$modelBook = Book::find()->innerJoin('author','author.id = book.author_id')->where(['book.id'=>1])->one();
$modelAuthor = Author::findOne(['id'=>$modelBook->author_id]);

The problem:

How can I get 2 activerecord model Book and Author with just only one mysql execute?

I know that we can use with() function, but it spend another query SELECT ...IN(...) to get second model, although we have sufficient data from join query

Is there a more effective solution ?

ActiveRecord are for model extendinng the ActiveRecord classe You seems are using a query and not a "model" so i suggest you of use activeDataProvider.

You can refer the models managed by dataProvider using getModels() function

       $provider = new SqlDataProvider([
         ......
    ]);



    // returns an array of data rows
    $models = $provider->getModels();

see this guide and reference for detail

http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html

Try this :

With approach is not slower in case of performance.

$modelBook = Book::find()->with('YOUR_RELATION_NAME_HERE')->findByPK(id);