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
Examples:
...
/* Images Model */
namespace Modules\Ambience\Common\Models;
class Images extends Model {
public function initialize(){
$this->hasOne('attachment_id','\Modules\Ambience\Common\Models\Attachments','id',['alias'=>'Attachments']);
}
}
/* 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
$image->save();
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.