We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Can't delete related model. 1-n relation.

Hi everybody! I have 2 simple models:

<?php

namespace My\Model;

class Choice extends \Phalcon\Mvc\Model {

    protected id;
    protected option_id;

    public function initialize()
    {
        $this->hasOne('option_id', 'My\Model\Option', 'id', ['alias' => 'Option']);
    }
}

A choice must have 1 selected option or null (nothing selected).

<?php

namespace My\Model;

use Phalcon\Mvc\Model\Validator\PresenceOf;

class Option extends \Phalcon\Mvc\Model {

    protected id;
    protected $name;

    public function initialize()
    {
        // I don't need for a "belongTo"
    }

    public function validation() {
        $this->validate(new PresenceOf([
            'field'   => 'name',
            'message' => $di['translator']->translate('Name can\'t be empty!')
        ]));
    }
}
$choice = new \My\Model\Choice();
$option = \My\Mode\Option::findFirst("name = 'awesome'");

$choice->Option = $option;
$choice->save();

How can I delete an Option of an existed Choice (set null to option_id)?

I tried

$choice = \My\Model\Choice::findFirst(1);
$choice->Option = null;
$choice->save();

This doesn't work. This tries to create a new empty instance of \My\Model\Option and save it. Of course, it throws a validation message that the name is empty.

$choice->Option->delete();


2.3k

No, this will delete full row from table option. I need to set null to option_id at choice table.

check ur database ,may be the option_id column is `not null'?

No, this will delete full row from table option. I need to set null to option_id at choice table.



2.3k

No, everything is ok. I haven't not null. I will use simple sql query like UPDATE choice SET option_id = NULL WHERE ... :(

check ur database ,may be the option_id column is `not null'?

No, this will delete full row from table option. I need to set null to option_id at choice table.

How about set option_id to 0 instead of null?

No, everything is ok. I haven't not null. I will use simple sql query like UPDATE choice SET option_id = NULL WHERE ... :(

check ur database ,may be the option_id column is `not null'?

No, this will delete full row from table option. I need to set null to option_id at choice table.



2.3k

Foreign key to 0? Seriously?

I have thesame question... any solution?