Yii2 with 和 joinWith 的区别

技巧库 · forecho · 于 6年前 发布 · 18312 次阅读

先确保 Topic 有 getComments() 方法

class Topic extends \yii\db\ActiveRecord
{
    ...
    public function getComments()
    {
        return $this->hasMany(Comment::className(), ['topic_id' => 'id']);
    }
}

joinWith()

Topic::find()->joinWith('comments');

// 输出的 SQL
SELECT `topic`.* FROM `topic` LEFT JOIN `comment` ON `topic`.`id` = `comment`.`topic_id`

with()

Topic::find()->with('comments');

// 输出的 SQL
SELECT * FROM `topic`
SELECT * FROM `comment` WHERE `topic_id` IN (1, 2, 3, 4, 5)

相关文档

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations

本文由 forecho 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。


如果这篇文章对您有帮助,不妨微信小额赞助我一下,让我有动力继续写出高质量的教程。

共收到 3 条回复 Yii2
ppker#16年前 0 个赞

是的 这个2个方法很重要的 待我认真阅读下文档

Kittyfamous#26年前 0 个赞

@forecho joinWith 有必要么? 效率也差吧,据说淘汰了?

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册