Cakephp 3查询包含连接?

时间:2015-07-23 15:31:44

标签: cakephp cakephp-3.0

我有3个表:UsersArticlesCategories以及联接表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'));
}

0 个答案:

没有答案