我为班级workAbroads
的班级WorkType
和workType
关系声明了WorkAbroad
关系:
class WorkType extends \yii\db\ActiveRecord
{
...
public function getWorkAbroads()
{
return $this->hasMany(WorkAbroad::className(), ['WorkTypeID' => 'ID']);
}
}
class WorkAbroad extends \yii\db\ActiveRecord
{
...
public function getWorkType()
{
return $this->hasOne(WorkType::className(), ['ID' => 'WorkTypeID']);
}
}
我想测试这种关系的比例。怎么做得好?
假设我创建了一个$workType
个对象和一百个$workAbroads
个对象。
我希望以下表达式将返回$workAboards
个对象的数组:
$workAboards = $workType->getWorkAbroads(); // The SQL query is always executed
// $workAboards = $workType->workAbroads; // The SQL query will be executed once
然后检查成功:
assertEquals(100, count($workAbroads));
相反,我收到以下错误:
Failed asserting that 1 matches expected 100
我知道我可以通过查询以下为真的所有ActiveRecord对象WorkAbroad
来测试关系:
'WorkTypeID' => $workType->ID
但我想了解为什么第一种方法不起作用?..
我将非常感谢这些信息。谢谢大家。
答案 0 :(得分:1)
$workType->getWorkAbroads()
将返回ActiveQuery
个对象,而不是WorkAbroad
个对象的数组,您应该尝试:
$workAboards = $workType->getWorkAbroads()->all();
但是如果你只想计算相关记录,你应该使用它:
assertEquals(100, $workType->getWorkAbroads()->count());