cakephp-从两个不相关的表中获取结果
我已经在谷歌上搜索了一段时间,但是没有用。我发现可能的答案令人困惑,希望有人能帮我澄清 我有两个表(任务和安装),它们包含相似的数据,但不相同,两个表之间没有关系,只是它们都属于同一个分支。例如:cakephp-从两个不相关的表中获取结果,php,mysql,cakephp,Php,Mysql,Cakephp,我已经在谷歌上搜索了一段时间,但是没有用。我发现可能的答案令人困惑,希望有人能帮我澄清 我有两个表(任务和安装),它们包含相似的数据,但不相同,两个表之间没有关系,只是它们都属于同一个分支。例如: select id, branch_id, task_name, NULL as install_details, 'task' as type, to_be_billed, created from tasks_table UNION select
select
id,
branch_id,
task_name,
NULL as install_details,
'task' as type,
to_be_billed,
created
from
tasks_table
UNION
select
id,
branch_id,
NULL as task_name,
install_details,
'install' as type,
to_be_billed,
created
from
install_table
任务表
id
branch_id
task_name
to_be_billed
created
id
branch_id
install_details
to_be_billed
created
安装表
id
branch_id
task_name
to_be_billed
created
id
branch_id
install_details
to_be_billed
created
我试图弄清楚如何获得一个结果集,它将显示任意一个表中的每条记录,按创建日期顺序排列,并且只在“to_be_billed”列为“1”的地方
谁能给我一些指点吗
谢谢如果您试图使用一个DB查询获取数据,则需要使用UNION运算符 在这种情况下,您需要这两个查询具有相同的列,例如:
select
id,
branch_id,
task_name,
NULL as install_details,
'task' as type,
to_be_billed,
created
from
tasks_table
UNION
select
id,
branch_id,
NULL as task_name,
install_details,
'install' as type,
to_be_billed,
created
from
install_table
但这是一个相当肮脏的解决方案
如果我确切地知道您想要实现什么,也许我可以建议一个更好的答案。我假设您希望使用分支id获得结果,并且这两个表(任务和安装)与分支表有一些关系 我还假设Tasks和Installs表对于一个分支有多条记录
BranchTable->find()
->contain([
'Tasks' => [
'sort' => ['Tasks.created' => 'ASC']
]
])
->contain([
'Installs' => [
'sort' => ['Installs.created' => 'ASC']
]
])
->matching('Tasks', function ($q){
return $q->andWhere(['Tasks.to_be_billed' => 1]);
})
->matching('Installs', function ($q){
return $q->andWhere(['Installs.to_be_billed' => 1]);
})
->where(['Branch.id' => $foo]);
如果您的怀疑没有使用这些假设,请告诉我。谢谢您的回复。基本上,我试图得到一个结果集,它将两个表的信息结合在一起。列名不必相同。我想知道是否最好只做两个单独的查询,每个表一个,然后在foreach中对每个表的结果进行排序,这样我就可以按日期对它们进行排序。是的,您还可以将两个单独查询的结果合并到一个数组中,然后使用一些回调函数对其进行排序,例如(伪代码)
usort($array,function)($a,$b){return$a->created->getTimestamp()>$b->created->getTimestamp()})
是的,在我看来,从数据库中检索数据后,这似乎是一个需要解决的问题,而不是在查询本身中。好吧,你可以在这些条件下编写一个连接,看看它给你什么。日期有时间还是没有时间?以及man如何在两个表中记录?