Search code examples
phpphalconphalcon-orm

How efficiently this controller action can be written more in phalcon?


I am trying to delete data from two tables which are associated with each other but I want to know that how it can be written more efficiently in phalcon as I am doing it right now through the normal PHP loop method.

Here is the Action code as :

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

I would like to know a neat and efficient and easy method to do this in phalcon model methods etc?

Note : It works as you can see but the problem is it messes with my executions speeds i.e (the performance of the web page goes from loading in a second to perform the action and then redirects back to the page goes to more like 2 seconds) as I would say or quite more likely from 500ms to 1000ms etc and that I do not want. I want to maintain the fast speed and to solve this issue without using the loop which in turn iterates over the records which are not related to the parent record too which wastes time. I mean I want strictly to get all associated records from the child table and delete those directly without compromising the performance (times).


Solution

  • You could create a relationship inside the model class. You can then set cascade actions to automatically delete related records.

    Creating the relationship and setting the cascade setting

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

    Updating the controller

    You no longer need to do anything other than delete the poll record.

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

    Read and learn more about this here:

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