我在控制器中使用find()并在行为回调中结合beforeFind()时遇到数据完整性问题。 WHERE Submissions.site_id没有像它应该的那样添加到WHERE子句中。我根据WHERE子句的设置位置得到不同的结果集。
在我的SubmissionsController中:
public function index()
{
$query = $this->Submissions->find('all')
->where(['user_id' => $this->Auth->user('id')])
->contain(['Users', 'Categories']);
$this->set('submissions', $this->paginate($query));
}
在我的beforeFind()模型回调中(附加为' TenantBehavior'到
$query->where([$this->_table->alias().'.'.'site_id' => 3]);
问题在于,通过上述内容,生成的SQL会将" WHERE"作为JOIN条件的AND的子句是这样的,而不是实际的WHERE:
...
FROM
submissions Submissions
INNER JOIN users Users ON (
Users.id = (Submissions.user_id)
AND Users.site_id = 3
)
INNER JOIN categories Categories ON (
Categories.id = (Submissions.category_id)
AND Categories.site_id = 3
)
WHERE
user_id = 315
如果我删除了beforeFind() - > where,而是将它放在控制器上 - >其中我得到了预期的SQL和结果集,如下所示:
...
FROM
submissions Submissions
INNER JOIN users Users ON (
Users.id = (Submissions.user_id)
AND Users.site_id = 3
)
INNER JOIN categories Categories ON (
Categories.id = (Submissions.category_id)
AND Categories.site_id = 3
)
WHERE
(
user_id = 315
AND Submissions.site_id = 3
)
思考?建议?
EDIT
作为@ndm的建议,我开始更新并提供更多上下文。在这样做的过程中,我发现(就像一个白痴)我错过了{'提交表'上的$this->addBehavior('Tenant');
。模型。添加这当然解决了这个问题。
答案 0 :(得分:0)
$query = $this->Submissions->find('all', [
'conditions' => [
'user_id' => $this->Auth->user('id')
],
'contain' => [
'Users',
'Categories',
]
]);
将条件作为内联数组传递将解决您的问题,并在条件正确的情况下追加beforeFind()。