I have recently discovered a strange ?bug? Lets say my model has category and subcategory like this:
<?php
namespace XXX\Inventory\Models;
use Phalcon\Mvc\Model;
class Inventory extends Model
{
public $id;
public $categoryId;
public $subCategoryId;
// other fields here
public function initialize()
{
$this->setSource('inventory');
$this->belongsTo('categoryId', InventoryCategory::class, 'id', [
'alias' => 'category',
]);
$this->belongsTo('subCategoryId', InventorySubCategory::class, 'id', [
'alias' => 'subCategory',
]);
$this::setup(['castOnHydrate' => true]);
}
public function toArray($columns = null)
{
$result = parent::toArray($columns);
$result['id'] = (int)$this->id;
if (!empty($this->category)) {
$result['category'] = $this->category->toArray();
}
if (!empty($this->subCategory)) {
$result['subCategory'] = $this->subCategory->toArray();
}
return $result;
}
}
It becomes impossible to save relationships by setting
$entity = Inventory::findOneById(12);
$entity->categoryId = 1;
$entity->subCategoryId = 2;
$entity->save();
Every other field saves properly but not categoryId nor subCategoryId. There are 2 workarounds of this problem:
-
Comment out toArray those lines:
if (!empty($this->category)) { $result['category'] = $this->category->toArray(); } if (!empty($this->subCategory)) { $result['subCategory'] = $this->subCategory->toArray(); }
- Remove relationships:
$this->belongsTo('categoryId', InventoryCategory::class, 'id', [ 'alias' => 'category', ]); $this->belongsTo('subCategoryId', InventorySubCategory::class, 'id', [ 'alias' => 'subCategory', ]);
Is it suppose to be working like this or am I missing something?