Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Dynamic insert

Hello. I am making application with database privileges system. The main thing is that user has his own privileges set in MySQL and depending on them he can use system. So i am trying to make inserts to table, in which user has not all column rights, but phalcon returns access violation error. Error reason is that phalcon tries to insert ALL columns, even if some of them are not set in the object. Attributes skip doesnt help here, because user privileges in tables are dynamic. Is there any other solution to save record with partial columns?

P.S. I tried both ways : $newPayment->create() with set properties and $newPayment->create($post).



1.5k
Accepted
answer
edited Jan '16

Phalcon definitely doesn't take into account column priveleges but dynamic update might help. You can set it for every model individually or set it in the Models Manager DI service to make it global:

$di->setShared(
    "modelsManager",
    function () use ($di) {
        $modelsManager = new \Phalcon\Mvc\Model\Manager();

        $eventsManager = $di->getShared("eventsManager");

        $eventsManager->attach(
            "modelsManager:afterInitialize", 
            function(\Phalcon\Events\Event $event, \Phalcon\Mvc\Model\ManagerInterface $modelsManager, \Phalcon\Mvc\ModelInterface $model) {
                $modelsManager->useDynamicUpdate($model, true);
            }
        );

        $modelsManager->setEventsManager($eventsManager);

        return $modelsManager;
    }
);

You can also use my Composer package (sidroberts/phalcon-events) which has the event as a class (see https://github.com/SidRoberts/phalcon-events/blob/master/src/ModelsManager/ModelDynamicUpdate.php):

$di->setShared(
    "modelsManager",
    function () use ($di) {
        $modelsManager = new \Phalcon\Mvc\Model\Manager();

        $eventsManager = $di->getShared("eventsManager");

        $eventsManager->attach("modelsManager", new \Sid\Phalcon\Events\ModelsManager\ModelDynamicUpdate());

        $modelsManager->setEventsManager($eventsManager);

        return $modelsManager;
    }
);

Obivously, you'll still run into nasty problems if you update a column that is priveleged but that should work.



324

In my case, dynamic update is not working as I want, so i found a bit better solution, added this function in every model. Of course now i see that i could set this in events manager.. :)

public function beforeCreate(){ $this->skipAttributesOnCreate(HelperController::getSkipFields(get_class($this))); }