doulan4371 2016-04-28 02:42
浏览 37

如何在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 ?

  • 写回答

2条回答 默认 最新

  • doukuizuo1795 2016-04-28 07:29
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离