phalcon-在将结果集转换为数组时没有定义关系?[英] phalcon - Relationships not defined when converting resultset to array?

问题描述

我用两种方法测试过:

第一个:

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);

所以我不用在视图端做计算,只需要输出就可以了

推荐答案

是的,当您将结果集转换为数组时,只会转换标量值.但是为了向模型添加计算属性,无需将其转换为数组,您可以根据需要更改或创建新属性,并且仅当您调用例如 $project->save() 时才会将其保存到数据库中,并且只是属性匹配的列名将被存储在数据库中.

对于添加计算属性,我建议您使用事件 afterFetch 为从数据库中检索到的每个模型触发:

class Projects extends \Phalcon\Mvc\Model
{
    ...
    public function afterFetch()
    {
        //Adds a calculated property when a project is retrieved from the database
        $totalTodos = Todos::count("project_id = $this->id");
        $completeTodos = Todos::count("project_id = $this->id AND status_id = 9");
        $this->percentageDone = round(($completeTodos / $totalTodos) * 100, 2);
    }
}

本文地址:https://www.itbaoku.cn/post/1739805.html