@emiliodeg Thank you for the anwser, but I am not sure if it is correct.
Here are my models:
An article
/**
* Class Articles
* Stores articles available on the website
*
* @package Website\Models
*/
class Articles extends Model
{
// [...]
/**
* ID
* @var integer
*/
public $id;
/**
* Name
* @var string
*/
public $title;
// [...]
/**
* Define relationships to Users and Permissions
*/
public function initialize()
{
// Categories
$this->hasMany('id', __NAMESPACE__ . '\Categories2Articles', 'article_id', [
'alias' => 'categories2articles',
'foreignKey' => [
'message' => 'Article cannot be deleted because it\'s used on Categories2Articles'
]
]);
$this->hasManyToMany(
'id',
__NAMESPACE__ . '\Categories2Articles',
'article_id',
'category_id',
__NAMESPACE__ . '\Categories',
'id'
);
// Tags
$this->hasMany('id', __NAMESPACE__ . '\Tags2Articles', 'article_id', [
'alias' => 'tags2articles',
'foreignKey' => [
'message' => 'Article cannot be deleted because it\'s used on Tags2Articles'
]
]);
$this->hasManyToMany(
'id',
__NAMESPACE__ . '\Tags2Articles',
'article_id',
'tag_id',
__NAMESPACE__ . '\Tags',
'id', [
'alias' => 'tags',
'params' => [
'order' => 'name ASC',
// 'conditions' => 'is_active = 1',
// 'cache' => ['lifetime' => 3600, 'key' => 'current-active-post-tags']
]
]
);
}
}
An e.g. categories:
/**
* Class Categories
* Stores categories available on the website
*
* @package Website\Models
*/
class Categories extends Model
{
/**
* ID
* @var integer
*/
public $id;
/**
* Name
* @var string
*/
public $name;
/**
* Slug
* @var string
*/
public $slug;
/**
* Define relationships to Users and Permissions
*/
public function initialize()
{
$this->hasMany('id', __NAMESPACE__ . '\Categories2Tutorials', 'category_id', [
'alias' => 'categories2tutorials',
'foreignKey' => [
'action' => Relation::ACTION_CASCADE,
'message' => 'Category cannot be deleted because it\'s used on Categories2Tutorials'
]
]);
}
}
and model describing their relationship:
class Categories2Articles extends Model
{
/**
* ID
* @var integer
*/
public $id;
/**
* Name
* @var string
*/
public $category_id;
/**
* Slug
* @var string
*/
public $article_id;
/**
* Sets table name
*
* @return string
*/
public function getSource(): string
{
return "categories2articles";
}
/**
* Define relationships to Users and Permissions
*/
public function initialize()
{
$this->belongsTo(
'category_id',
__NAMESPACE__ . '\Categories',
'id', [
'alias' => 'categories',
'reusable' => true
]
);
$this->belongsTo(
"article_id",
__NAMESPACE__ . '\Articles',
'id', [
'alias' => 'articles',
'reusable' => true
]
);
}
}
So,
when I am inserting new article... relation aliases seem to work fine.
But,
when I am updating existing article... relation aliases seem to not work at all.
I can try to insert Categories2Articles
records, but why?