【发布时间】:2025-12-24 09:40:11
【问题描述】:
我有以下表格:活页夹、文档、用户、docs_users。 Doc belongsTo Binder,Doc hasAndBelongsToMany User。
我想为当前登录的用户获取活页夹及其相关文档(docs_users 表中的相关 user_id)。
我已经尝试使用 Containable 和 find('all') 连接、条件等,但我不知道如何删除来自未在 docs_users 表中关联的用户的文档。
此代码不起作用:
$binders = $this->Binder->find(
'all',
array(
'joins' => array(
array(
'table' => 'binders_users',
'alias' => 'BindersUser',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array(
'BindersUser.binder_id = Binder.id',
'BindersUser.user_id = ' . $this->Auth->user('id')
)
),
array(
'table' => 'docs',
'alias' => 'Doc',
'type' => 'left',
'foreignKey' => false,
'conditions'=> array(
'Doc.binder_id = Binder.id',
)
),
array(
'table' => 'docs_users',
'alias' => 'DocsUser',
'type' => 'left',
'foreignKey' => false,
'conditions'=> array(
'DocsUser.doc_id = Doc.id',
'DocsUser.user_id = ' . $this->Auth->user('id')
)
)
),
'recursive'=>0
)
);
$this->set('binders', $binders);
这也不是:
$this->Binder->recursive = 2;
$this->Binder->Behaviors->attach('Containable');
$this->Binder->contain(array(
'Branch',
'Doc' => array(
'User' => array(
'DocsUser' => array(
'conditions' => array('id = "17"')
)
)
)
));
$binders = $this->Binder->find('all');
经验丰富的专业人士的任何帮助都会很棒!谢谢!
替代/简化解决方案?
如果我只想获取用户有权访问的活页夹,这很有效。短而甜。但是,它仍然会发送所有相关的文档,这不是我想要的行为。它只需要传递用户有权访问的文档(如前所述)。
$binders = $this->Binder->find(
'all',
array(
'joins' => array(
array(
'table' => 'binders_users',
'alias' => 'BindersUser',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array(
'BindersUser.binder_id = Binder.id',
'BindersUser.user_id = ' . $this->Auth->user('id')
)
)
)
)
);
【问题讨论】:
-
如果您将
debug设置为 2 并查看生成的查询蛋糕可能会有所帮助。然后进行所需的更改以获得所需的结果。 -
另外,您能否将您的数据库架构粘贴到 pastebin 或其他东西上并链接它。
-
好主意。这里是:pastebin.com/0bRn9USD 我现在没有使用 ACL 表,因为我认为在记录级别这样做会创建一个庞大的数据库。有点违背了目的。
-
如果@Leo 的方法不适合你,为什么不把它分成两个查询来得到你想要的确切输出呢?我发现在使用 Cake 和 $this->find() 时,我往往会忘记这样一个事实,即最终都是 SQL,而且你总是可以分解问题而不是在一个查询中解决所有问题 :)跨度>
-
JohnP - 你是对的。我只是不知道如何在 CakePHP 的框架内完成这个。还是有点绿。
标签: cakephp cakephp-1.3