4

我需要一些关于 CakePHP 2.2.3 的帮助。

我有的

我目前有以下设置:

Post 有很多 Attachment

它工作正常,页面由 2 个查询生成:

SELECT *, `Post`.`id` 
FROM `posts` AS `Post` 
WHERE 1 = 1 
ORDER BY `Post`.`created` DESC

SELECT 
    `Attachment`.`id`, 
    `Attachment`.`post_id`, 
    `Attachment`.`created` 
FROM 
    `attachments` AS `Attachment` 
WHERE 
    `Attachment`.`post_id` IN (1, 2, 3, ..., n) 

我想要的是

我想将关系扩展如下:

Post 有很多 Attachment;每个都Attachment 属于 Type

而且我不知道让CakePHP 跟随它的热度。
基本上,我需要的是:

SELECT *, `Post`.`id` 
FROM `posts` AS `Post` 
WHERE 1 = 1 
ORDER BY `Post`.`created` DESC

SELECT 
    `Attachment`.`id`, 
    `Attachment`.`post_id`, 
    `Attachment`.`created`, 
    `Type`.`title`, `Type`.`icon` 
FROM 
    `attachments` AS `Attachment` 
LEFT JOIN 
    `types` AS `Type` 
    ON (`Attachment`.`type_id`=`Type`.`id`) 
WHERE 
    `Attachment`.`post_id` IN (1, 2, 3, ..., n) 

注意LEFT JOIN types添加。

所以我在第二个查询中得到了相应的类型数据。我知道我可以循环或使用->query()调用来获取数据,但我希望这尽可能有效和灵活。

问题

我尝试了ContainableModel Unbinding 技巧和这个),但没有成功。我尝试了不同的选项组合,我相信我什至删除了连接。这是我PostsController现在的样子。

class PostsController extends AppController {
    public function index() {

        $this->Post->unbindModel(array('hasMany' => array('Attachment')));
        $this->Post->Attachment->unbindModel(array('belongsTo' => array('Type')));

        $this->Post->bindModel(array(
            'hasMany' => array(
                'Attachment' => array(
                    'className'  => 'Attachment',
                // when uncommented, throws the "Unknown column Post.id" SQLSTATE error
                //  'conditions' => array('Post.id' => 'Attachment.post_id'),
                    'foreignKey' => false,
                ),
            ),
        ));
        $this->Post->Attachment->bindModel(array(
            'belongsTo' => array(
                'Filetype' => array(
                    'className'  => 'Filetype',
                //  'conditions' => array('Type.id' => 'Attachment.type_id'),
                    'foreignKey' => false,
                ),
            ),
        ));
        $all = $this->Post->find('all', array(
            'joins' => array(
                array(
                    'table' => 'users',
                    'prefix' => '',
                    'alias' => 'User',
                    'type' => 'INNER',
                    'conditions' => array(
                        'User.id = Post.user_id',
                    )
                ),
            ),
            'contain' => array('Attachment', 'Type'),
            'conditions' => array(),
            'fields' => array('*'),
            'order' => 'Post.created ASC'
        ));
        var_dump($all);exit;
    }
}

但它只是在循环中每次迭代运行一个额外的查询并获取所有附件:

SELECT `Attachment`.`id`, ... 
FROM `attachments` AS `Attachment` 
WHERE 1 = 1 

当我取消注释此关联的条件时,它会抛出 SQLSTATE “Column Post.id not found error” - 我猜是因为这里没有加入 Post 表。

我需要帮助进行设置。

请帮忙!谢谢

更新

我已按如下方式更改了控制器。请注意没有bindModel/unbindModel代码,关系是在模型类中设置的(在这种情况下是否正确?)。

class PostsController extends AppController {
    public function index() {
        $options = array(
            'contain' => array(
                'Post',
                'Type'
            ),
            'order' => 'Post.created DESC',
            'conditions' => array(
            //  'Post.title LIKE' => 'my post'
            )
        );

    //  The following throws "Fatal error: Call to a member function find() on a non-object"
    //  $posts = $this->Attachment->find('all', $options); 

    //  So I had to use $this->Post->Attachment instead of $this->Attachment
        $posts = $this->Post->Attachment->find('all', $options);
        $this->set(compact('posts'));
    }   
}

这是Attachment模型:

class Attachment extends AppModel {
    public $belongsTo = array(
        'Type' => array(
            'className' => 'Type',
            'foreignKey' => 'type_id',
        ),
        'Post' => array(
            'className' => 'Post',
            'foreignKey' => 'post_id',
        ),
    );
}

上面的代码运行这个查询:

SELECT 
    `Attachment`.`id`, `Attachment`.`type_id`, `Attachment`.`post_id`, `Attachment`.`created`, 
    `Type`.`id`, `Type`.`title`, 
    `Post`.`id`, `Post`.`text`, `Post`.`created` 
FROM 
    `attachments` AS `Attachment` 
    LEFT JOIN `types` AS `Type` ON (`Attachment`.`type_id` = `Type`.`id`) 
    LEFT JOIN `posts` AS `Post` ON (`Attachment`.`post_id` = `Post`.`id`) 
WHERE 
    1 = 1 
ORDER BY 
    `Post`.`created` ASC

一切都是关于这里的附件。我的意思是帖子加入了附件,所以如果帖子没有附件,它不会被退回。这可能是因为Attachment->find()从附件的角度来看,呼叫是如此。我想它应该是:

// ...
FROM 
    `posts` AS `Post`
    LEFT JOIN `attachments` AS `Attachment`  ON (`Attachment`.`post_id` = `Post`.`id`) 
    LEFT JOIN `types` AS `Type` ON (`Attachment`.`type_id` = `Type`.`id`) 
// ...

但这行不通,不是吗?您会看到posts,attachmentstypes,但它们确实具有不同的关系类型。最初,我已经发布了 CakePHP 运行的这两个单独的查询——这一定是有原因的。

更新2

我仍然相信这一切都是为了在初始设置中将第二个查询更改为Attachment模型(请参阅我想要的部分)。所以我会得到附件类型以及附件本身。我的意思是在那种情况下,左连接typesattachments不会破坏任何数据库关系逻辑,是吗?
我只是想确保没有办法通过一个复杂但单一的find()调用来做到这一点。

4

2 回答 2

3

每当 Cake 看到 hasMany 关系时,它会自动创建多个查询来拉取数据。在构建这些查询时,它会查找可以左连接到它的关系(hasOne 和 belongsTo)。

由于 Cake 无法为您完成此操作,因此您需要自己合并它们。

public function index() {
  $posts = $this->Post->find('all');
  // get all attachments for all found posts
  $attachments = $this->Post->Attachment->find('all', array(
    'contain' => array('Type'),
    'conditions' => array('Post.id' => Set::extract('/Post/id', $posts)
  ));
  // now join them to the posts array
  foreach ($posts as $key => $data) {
    $postId = $data['Post']['id'];
    // append any data related to this post to the post's array
    $posts[$key] += Set::extract("/Attachment[post_id=$postId]/..", $attachments);
  }
  $this->set(compact('posts'));
}

$attachments这不是最有效的方法,因为您将多次遍历数组,但我相信您明白了。

于 2012-12-17T21:04:37.277 回答
0

试试 hasMany 中的 finderQuery。例如:在 Post 模型中,

public $hasMany = array(
    'Attachment' => array(
        'className' => 'Attachment',
        'foreignKey' => 'post_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '                            
             SELECT 
                 `Attachment`.`id`, 
                 `Attachment`.`post_id`, 
                 `Attachment`.`created`, 
                 `Type`.`title`, 
                 `Type`.`icon` 
                  FROM 
                 `attachments` AS `Attachment` 
                  LEFT JOIN 
                 `types` AS `Type` 
                  ON (`Attachment`.`type_id`=`Type`.`id`) 
                   WHERE 
                          `Attachment`.`post_id` IN (1, 2, 3, ..., n)
                ',
        'counterQuery' => ''
    )
于 2013-06-12T09:47:07.377 回答