CakePHP - 使用contain获取关联数据

当使用 find() 方法查询数据时,默认不包含任何关联数据。
对于 belongsTohasOne 关系,在获取关联数据时只能使用 selectwhere 从句,其他类型的关联关系则可以使用Query对象提供的所有从句。

contain

加载Primary Model数据及其关联的Model数据。
contain默认使用LEFT JOIN查询,在Table类中定义。
contain中的查询只限制关联Model自身,不能限制Primary Model。

//As an option to find()
$this->Articles->find('all', [
    'contain' => ['Authors', 'Comments']
]);

//As a method on the query object
$this->Articles->find()
                ->contain(['Authors', 'Comments'])
                ->all();

//多级关联
$this->Articles->find()
                ->contain(['Authors'=>['Profiles'], 'Comments'])
                ->all();
//or
$this->Articles->find()
                ->contain(['Authors.Profiles', 'Comments'])
                ->all();

//Rest the containments on a query
$query = $this->Articles->find();
$query->contain(['Authors', 'Tags'], true);
//Authors hasMany Articles
//结果集中的关联Model数据(articles)为多维数组
$this->Authors
        ->find()
        ->select(['id', 'name'])
        ->contain([
            'Articles' => [
                'fields' => ['id', 'title', 'author_id'], //必须包含外键
                'conditions' => ['Articles.title LIKE' => '%测试%'],
                'sort' => ['Articles.created' => 'DESC'] //sort, not order
            ]
        ])
        ->all();

//Articles belongsTo Authors
//结果集中的关联Model数据(author)为一维数组
$this->Articles
        ->find()
        ->select(['id', 'title']) //外键不必须
        ->contain([
            'Authors' => function($q) { //Callback形式,Prior to 3.5
                return $q->select(['id', 'name']);
            }
        ])
        ->all();

//3.5+
->contain('Authors', function($q) {
    return $q->...;
});

猜你喜欢

转载自blog.csdn.net/hwhsong/article/details/78353041