问题
I am developing a system that holds reports from customer's computers and displays failures in a list. I am attempting to write a query that locates all systems that have currently failed or have failures in the past.
My model for Computers
has a field that says last_report_pass
that allows me to quickly find computers that failed on the current day. My Reports
are associated with a computer ID and has a field called status
that says whether it was a pass or fail.
I am attempting to write a query that will only show last_report_pass
being 0
, or failed, or show it if it has reports that were found and joined (meaning there were previous failures).
Here was my idea:
$computers = $this->Computers->find('all', [
'conditions' => [
'last_report_pass' => '0',
'COUNT(Reports) NOT' => '0'
],
'contain' => [
'Reports' => [
'conditions' => [
'status' => '0'
]
]
);
I do not know what to do from here. I could probably write this in SQL but am trying to stick with Cake's ORM Query Builder. Thanks in advance!
回答1:
You will need to use matching
its similar to contain, but it will filter by associated data:
It will be something like this
$query->distinct(['Computers.id'])
->matching('Reports', function ($q) {
return $q->where(['Reports.last_report_pass' => 0]);
});
Its important to notice that you will also have to contain
the Reports
table if you need to display some data which is on this table.
Reference
来源:https://stackoverflow.com/questions/44220965/cakephp-query-conditional-based-on-contain-field