简体   繁体   English

Yii2渴望加载不起作用

[英]Yii2 eager loading not working

I have two entities in my database which are related by a one to many relationship: "User" and "Ad" I have generated model classes using gii. 我的数据库中有两个实体,它们之间存在一对多关系:“用户”和“广告”,我已经使用gii生成了模型类。 This is what I have in my model class for User: 这是我的用户模型类中的内容:

public function getAds()
{
    return $this->hasMany(Ad::className(), ['user' => 'id']);
}

and for my Ad model: 对于我的广告模型:

public function getUser0()
{
    return $this->hasOne(User::className(), ['id' => 'user']);
}

according to Yii2 documentation, In the controller when I do 根据Yii2文档,当我在控制器中

$ads = Ad::find()->all();
var_dump($ads[0]->user);

It should eagerly load user data from the DB but I only get the foreign key (1). 它应该从数据库急切地加载用户数据,但是我只得到外键(1)。 Even when I try 即使我尝试

$ads = Ad::find()->with('user0')->all();
var_dump($ads[0]->user);

Its still the same. 它仍然一样。

thanks. 谢谢。 If I want to send Ads and their related user data by xml in an ActiveController, do I have to do something like this: 如果我想在ActiveController中通过xml发送广告及其相关的用户数据,是否需要执行以下操作:

$t = array();
    foreach ($ads as $ad) {
        $t[] = [$ad, $ad->user0];
    }
    return $t;

Or there is a more straightforward way to do that? 还是有更简单的方法来做到这一点?

You are still getting Ad objects either with or without eager loading. 无论是否加载,您仍将获得Ad对象。

The difference is how the relations are populated, with lazy loading the relations are only loaded when they are accessed. 区别在于关系的填充方式,延迟加载仅在访问关系时加载。

$ads = Ad::find()->all();
foreach ($ads as $ad) {
    var_dump($ad->user0); // query to load user record here
}

With eager loading they are populated up front. 随着热切的装载他们被预先填充。

$ads = Ad::find()->with('user0')->all();
foreach ($ads as $ad) {
    var_dump($ad->user0); // user0 already populated, no query
}

可能您需要joinWith $ads = Ad::find()->joinWith('user0')->all();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM