先确保 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 中国大陆许可协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。
如果这篇文章对您有帮助,不妨微信小额赞助我一下,让我有动力继续写出高质量的教程。