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.

Validate model FK field using default value

Hello guys!

I got such a strange issue... Defined one-to-many relation in DB between "profile" and "user" entities connected by "profileId" field. Then I had set the default value for "profileId" to 2. This number tells that if we create a new user the specific profile will be assigned to him automatically.

So how to organize this behavior using FK-check in models? I mean that one: $this->belongsTo('profileId', 'Profile', 'id', array('alias' => 'Profile', 'foreignKey' => true));

For now creation of a user gives such an error: "Value of field "profileId" does not exist on referenced table" This is because of that mentioned FK-check runs the query to DB to check that specific profile already exists. But it tries to ensure this by querying with the part similar to "... WHERE id = default". Of course, this query fails and gives us an error.

Already tried to $this->skipAttributesOnCreate(array('profileId')) but the problem still persists. I guess it doesn't affect the FK-checker...

Hope for your help! Thanks! Btw sorry for my english...



631
Accepted
answer

Hi,

try setup default value in your model User to profileId property.

class User extends \Phalcon\Mvc\Model {

    protected $profileId = 2;

    // other stuff...

}

OK, set it up that way. Thanks!