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

Storing Related Records Gives Error

I follow the example shown here I have hasMany relation.

Unfortunately I get id is required (no validation rule for this column) error while trying to add a new record to the database with related records. If I don't use related records, I can add each data seperately to my database without any error.

Is this a bug or I'm doing something wrong? I'm trying to add a record, I am not trying to edit it. Why do I get id is required error? Shouldn't an ID automatically assign to it?

id is the primary column in my database.

I have 3 models

  • Categories
  • Features
  • Options

Categories

$this->belongsTo("parent_id", "App\\Models\\Categories", "id", ["alias" => "parent"]);
$this->belongsTo("id", "App\\Models\\Categories", "parent_id", ["alias" => "subs"]);
$this->hasMany("id", "App\\Models\\Features", "categories_id", ["alias" => "features"]);

Features

$this->belongsTo("product_categories_id", "App\\Models\\Categories", "id", ["alias" => "category"]);
$this->hasMany("id", "App\\Models\\Options", "features_id", ["alias" => "options"]);

Options

$this->belongsTo("features_id", "App\\Models\\Features", "id", ["alias" => "feature"]);

Code in action

$record             = new Categories();
$record->parent_id  = 0;
$record->name       = $name;

// Features
$features = [];
// Color
$features[0] = new Features();
$features[0]->name = "Colors";

// Color options
$options = [];
$optons[0] = new Options();
$options[0]->name = "Blue";

$options[1] = new Options();
$options[1]->name = "Red";

// Assign to Color feature
$features[0]->options = $options;
unset($options);

// Size
$features[1] = new Features();
$features[1]->name = "Size";

// Size options
$options = [];
$options[0] = new Options();
$options[0]->name = "S";

$options[1] = new Options();
$options[1]->name = "M";

$options[2] = new Options();
$options[2]->name = "L";

$options[3] = new Options();
$options[3]->name = "XL";

// Assign to Size feature
$features[1]->options = $options;
unset($options);

// Assign features to the category
$record->features = $features;
unset($features);

// Save category
$record->save();

I guess I'm doing a mistake at relations level but I'm not sure at this point.

Show your code please.



2.3k
edited Feb '16

Show your code please.

Thanks for your reply, I hope that's enough

Which model is generating the error?



2.3k
edited Feb '16

Which model is generating the error?

It seems Features model is generating the error



2.3k

Ouch... I just realized Features table's id field is not AUTO_INCREMENT which caused all the trouble! Thanks for the assist Dylan.