如何有效地在phalcon中编写此控制器操作?

时间:2017-07-13 23:36:18

标签: php phalcon phalcon-orm

我正在尝试从两个相互关联的表中删除数据,但我想知道如何在phalcon中更有效地编写数据,因为我现在正在通过正常的PHP循环方法执行此操作。

以下是Action代码:

  public function deletepollAction($pollId)
    {

        $poll = new Polls();
        $data = $poll->findFirst($pollId);
        $data->delete();
        $options = PollsOptions::find();
        foreach ($options as $singleoption) {
        if ($singleoption->polls_id == $pollId) 
        {
        $option = new PollsOptions();
        $data = $option->findFirst($singleoption->id);
        $data->delete();
        }
        }
        $this->response->redirect("/poll");
    }

我想知道在phalcon模型方法中使用一种简洁有效的方法吗?

注意:它的工作原理你可以看到,但问题是它与我的执行速度混淆即(网页的性能来自加载一秒钟来执行操作然后重定向回来如我所说,或者更有可能从500毫秒到1000毫秒等,我不想要的页面更像是2秒。我想保持快速并且在不使用循环的情况下解决这个问题,而循环又迭代了与父记录无关的记录,这也浪费了时间。 我的意思是我要严格从子表中获取所有相关记录并直接删除它们而不影响性能(次数)。

2 个答案:

答案 0 :(得分:3)

您可以在模型类中创建关系。然后,您可以设置级联操作以自动删除相关记录。

创建关系并设置级联设置

var ipv6 = "9:9:9:9";

$scope.ipv6_pattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})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("INVALID IPV6 " + ipv6);
}

更新控制器

除了删除民意调查记录之外,您不再需要做任何其他事情。

class Polls extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany(
            'id',
            'PollsOptions',
            'polls_id',
            [
                'foreignKey' => [
                    'action' => \Phalcon\Mvc\Model\Relation::ACTION_CASCADE
                ]
            ]
        );
    }
}

在这里阅读并了解更多相关信息:

https://docs.phalconphp.com/en/3.2/db-models-relationships#cascade-restrict-actions

答案 1 :(得分:1)

public function deletepollAction($pollId)
{
    $data = Polls::findFirst($pollId);
    $data->delete();
    $options = PollsOptions::find([
        'polls_id = :pollsId:',
        'bind' => [
            'pollsId' => $pollId
        ]
    ]);
    $options->delete();
    $this->response->redirect("/poll");
}

不确定为什么你会发现这个PollsOptions一次,然后再次找到它们进行删除?它没有意义。最好只在数据库中设置,以便在删除PollsOptions时级联删除Polls,然后您将只有:

public function deletepollAction($pollId)
{
    $data = Polls::findFirst($pollId);
    $data->delete();
    $this->response->redirect("/poll");
}