如何在多个joinWiths之后获取活动记录中的每条记录?
$model = \common\models\opcr\OpcrKra::find()
->joinWith('opcrRoObjectives')
->joinWith('opcrRoObjectives.opcrFdObjectives')
->joinWith('opcrRoObjectives.opcrFdObjectives.opcrIndividuals');
我收到Trying to get property of non-object
错误。
foreach ($model->all() as $row) {
echo "<tr>"
. "<td></td>"
. "<td>" . $row->kra . "</td>"
. "<td>" . $row->opcrRoObjectives->id . "</td>" // error here
. "</tr>";
}
我试图显示$row->count()
,它只给了我预期的确切记录数。
答案 0 :(得分:2)
我使用eager loading解决了这个问题。
$authors = Author::find()->with('posts')->all(); // fetches the authors with their posts
foreach($authors as $author) {
echo "<h2>Author : " . $author->name . "</h2>";
echo "<ul>";
foreach($author->posts as $post) { // no query executed here
echo "<li>" . $post->title . "</li>";
}
echo "</ul>";
}
答案 1 :(得分:1)
您只需尝试此解决方案:
$model = \common\models\opcr\OpcrKra::find()
->joinWith('opcrRoObjectives')
->joinWith('opcrRoObjectives.opcrFdObjectives')
->joinWith('opcrRoObjectives.opcrFdObjectives.opcrIndividuals')
$result = $model->asArray()->all();
然后在你看来:
foreach ($model as $row) {
echo "<tr>"
. "<td></td>"
. "<td>" . $row->kra . "</td>"
. "<td>" . $row['opcrRoObjectives']['id'] . "</td>"
. "</tr>";
}