我用两种方法测试了它:
第一个:
class ProjectsController extends ControllerBase
{
public function indexAction()
{
$row = array();
$projects = Projects::find();
foreach ($projects as $project) {
foreach($project->employees as $employee){
echo "Employee: " . $employee->name;
}
}
exit;
}
}
输出:
Employee: Admin
第二个:
class ProjectsController extends ControllerBase
{
public function indexAction()
{
$row = array();
$projects = Projects::find();
$projects = $projects->toArray();
foreach ($projects as $project) {
foreach($project["employees"] as $employee){
echo $employee->name;
}
}
exit;
}
}
输出:
Notice: Undefined index: employees in app/controllers/ProjectsController.php on line 10
将结果集转换为数组时,关系不会添加到数组中,是否有解决方法将其添加到数组中?
我将结果集转换为数组的原因是编辑结果,例如计算进度或类似的结果,而不将其保存到数据库。
这样的事情:
foreach($projects as &$project){
//count all the todos.
$todos = Todos::find("project_id = '".$project["id"]."'");
$numberOfTodos = $todos->count();
//count all the todos that are done.
$todos = Todos::find("project_id = '".$project["id"]."' AND status_id = 9");
$numberOfDoneTodos = $todos->count();
$project["percentageDone"] = ($numberOfDoneTodos / $numberOfTodos) * 100;
var_dump($row);exit;
}
$this->view->setVar("projects",$projects);
因此,我不必在视图方面进行计算,只需输出
答案 0 :(得分:3)
是的,当您将结果集转换为数组时,只会转换标量值。 但是,为了向模型添加计算属性,无需将其转换为数组,您可以根据需要更改或创建新属性,并且只有在调用示例时才会将其保存到数据库中{{1只有与列名匹配的属性才会存储在数据库中。
为了添加计算属性,我建议您使用从数据库中检索的每个模型触发的事件$project->save()
:
afterFetch