Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q: Delete relations - best practice? #16

Open
exodus4d opened this issue Feb 7, 2016 · 0 comments
Open

Q: Delete relations - best practice? #16

exodus4d opened this issue Feb 7, 2016 · 0 comments

Comments

@exodus4d
Copy link

exodus4d commented Feb 7, 2016

Hi,

I´m looking for the most elegant/clean way, for deleting has-one relations.
Setup:

class CharacterModel extends BasicModel {
    protected $table = 'character';
    protected $fieldConf = [
        'characterLog' => [
            'has-one' => ['Model\CharacterLogModel', 'characterId']
       ]
    ];
}

class CharacterLogModel extends BasicModel {
    protected $table = 'character_log';
    protected $fieldConf = [
        'characterId' => [
            'type' => Schema::DT_INT,
            'index' => true,
            'unique' => true,
            'belongs-to-one' => 'Model\CharacterModel'
        ]
    ];
}

I have a character and character_log stored in DB.
Now i would like to delete the relational character_log entry and keep the character entry. Therefore I have a deleteLog(); method in the CharacterModel Class:

public function deleteLog(){
    if(is_object($this->characterLog)){
        $this->characterLog->erase();
        $test = $this->save();
        var_dump($test->cast());
        var_dump($this->cast());
    }
}

This works but it does not seem to be the "right" way :) - The $this->save() is required, after erasing the character_log relation, to get a "updated" character model without the log. The second var_dump() (var_dump($this->cast());) still has the relational object. Is there a way to "auto-save" $this when a relation object was removed?


Then i tried something like this:

if(is_object($this->characterLog)){
    $this->clear('characterLog');
    $test = $this->save();
    var_dump($test->cast());
    var_dump($this->cast());
}

This does not delete the character_log row, it just set characterId column to null. And finally i tried this:

if(is_object($this->characterLog)){
    $this->characterLog = null;
    $test = $this->save();
    var_dump($test->cast());
    var_dump($this->cast());
}

This works as well but in any case, i have to use the returned $test variable,$this is not automatically updated after save. Is there are more elegant way to achieve what i want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants