CakePHP 4 查询:带有嵌套表的 where 子句不起作用?

CakePHP 4 query: where clause with nested table not working?

提问人:Oliverstonq 提问时间:10/9/2023 最后编辑:ShadowOliverstonq 更新时间:10/24/2023 访问量:44

问:

我是第一次使用 CakePHP,我正在尝试做一个(非常简单的)查询,但我没有设法完成它。我已经设置了数据库的所有表,并且运行良好。现在,我有这个查询:

$CompaniesTable = $this->fetchTable('Companies'); 
$open_rounds = $CompaniesTable->find()->contain('Fundings' => ['FundingsFundingrounds']])->where(['Companies.fif_status_id IN' => [4, 5, 7], 'FundingsFundingrounds.round' => true])->limit(10);

在我看来,这应该有效,但是当我执行时,我得到:

SQLSTATE[42S22]:找不到列:“where 子句”中的 1054 未知列“FundingsFundingrounds.round”

如果我删除 'FundingsFundingrounds.round' => true,则查询效果很好。我创建了另一个查询来查看“FundingsFundingrounds.round”是否真的存在,是的,确实存在!

可能我错过了在这种情况下使用 where 子句的步骤,我希望有人能提供帮助!

php cakephp where-子句 cakephp-4.x

评论

0赞 Shadow 10/9/2023
如果这是一个mysql查询,那么我建议使用连接将FundingsFundingrounds表引入from子句。你必须在 cakephp 中做等效的事情。
0赞 Juan Carlos 10/9/2023
您尝试实现的 SQL 查询是什么?(此外,contain('Fundings' => ['FundingsFundingrounds']]) 中还有一个额外的方括号)
1赞 Greg Schmidt 10/10/2023
看起来您想使用匹配。代码中多余的方括号就好了。:-)

答:

0赞 wowDAS 10/24/2023 #1

检查是否在单独的 SQL 查询中选择了 Fundings 和 FundingsFundingrounds。 如果这是真的(我假设),那么您实际上已经执行了 3 个查询。 我猜你有关系:公司有很多资金有很多资金融资轮次 和资金融资轮次属于资金属于公司 属于“contain”中的关系 -> left join(默认) 'contain' 中的 hasMany 关系 ->单独的查询(默认)

尝试:

$open_rounds = $this->fetchTable('FundingsFundingrounds')
->find()
->contain('Fundings' => ['Companies']])
->where([
  'Companies.fif_status_id IN' => [4, 5, 7],
  'FundingsFundingrounds.round' => true,
])
->limit(10);

您始终可以选择一个优雅的子查询,也可以满足您的需求。