我有3个表:Users
,Articles
和Categories
以及联接表Articles_Categories
。以下是我目前的协会。它们是否正确?
CategoriesTable:
public function initialize(array $config)
{
$this->table('categories');
$this->belongsToMany('Articles', [
'alias' => 'Articles',
'foreignKey' => 'category_id',
'joinTable' => 'articles_categories',
'targetForeignKey' => 'article_id'
]);
}
ArticlesTable:
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
$this->hasOne('Users');
$this->belongsTo('Users');
$this->belongsToMany('Categories', [
'alias' => 'Categories',
'foreignKey' => 'article_id',
'joinTable' => 'articles_categories',
'targetForeignKey' => 'category_id'
]);
}
UsersTable:
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
$this->hasMany('Articles', [
'dependent' => true,
'cascadeCallbacks' => true,
]);
}
现在我在ArticlesController中有一个打印文章的视图动作......
在我想要的View操作中使用article_id获取作者的用户名以及相关类别但是我的查询返回所有文章
这是我的观点行动:
public function view($id = null)
{
$query = $this->Articles->find()->contain([
'Categories',
'Users' => function ($q) {
return $q
->select(['username']);
}
]);
$this->set(compact('query'));
}