CakePHP Query - Conditional Based on Contain Field

折月煮酒 提交于 2020-01-07 05:37:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!