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.

Need help Save hasOne relation

I have some Models :

Images :

$this->hasOne('attachment_id', '\Modules\Ambience\Common\Models\Attachments', 'id',['alias'=>'Attachments']);

Attachment :

$this->belongsTo('attachment_id', '\Modules\Ambience\Common\Models\Images', 'id',['alias'=>'Images']);

And this is my code :

$image = new Images();

$attachment = new Models\Attachments();

// init property of attachment

$image->Attachments = $attachment;

// init property of image


The message error is attachment_id is required. I dont know why while I have relations Thanks

edited Jul '15

There could be a few issues but here is what I would check first

1 . Double check to make sure you are referring to the related tables using the correct column names.

Just looking at your code above, it looks like there may be a reference issue on your relations. I can't be sure without seeing the actual model definitions/tables. If you wanted to post them, it would help a lot.

2 . When creating related records using Models, I would recommend using ->save() instead of create(). I've never had an issue doing it this way. Also, try referring to the attachments instead of attachments


/*  Images Model */
  namespace Modules\Ambience\Common\Models;

  class Images extends Model {
    public function initialize(){

/*  Attachments Model */
  namespace Modules\Ambience\Common\Models;

  class Attachments extends Model {
    public function initialize(){
      $this->belongsTo('id','\Modules\Ambience\Common\Models\Images','attchment_id',['alias' => 'Images']);

/*  Create your records */
$image = new Models\Images();

$attachment = new Models\Attachments();
$attachment->setProperty("Property Value");

// Attach related record
$image->attachments = $attachment; // not $image->Attachments = $attachment;

// init property of image

Also, if you still receive that error after you've verified the relations, etc.. check to see if the attachment_id within your images table is NOT NULL. If it is NOT NULL, try to alter the table to make that column allow null values or default it using beforeValidationOnCreate() to see if that has a different outcome.

it works. Thanks. But i think phalcon document is not clear very much


You're welcome. I'm glad I could help. The documentation does a fairly good job for most things but I do agree that they need some more examples in this area.