基于包含字段的条件

基于包含字段的条件

本文介绍了CakePHP查询-基于包含字段的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个系统,该系统可以保存来自客户计算机的报告,并在列表中显示故障.我正在尝试编写一个查询,以查找当前已发生故障或过去发生故障的所有系统.

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.

我的Computers模型有一个显示为last_report_pass的字段,该字段使我可以快速查找当天发生故障的计算机.我的Reports与计算机ID相关联,并且具有一个名为status的字段,该字段指示它是通过还是失败.

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.

我正在尝试编写一个仅显示last_report_pass0或失败的查询,或者显示是否包含已找到并加入报告(意味着以前有过失败)的查询.

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).

这是我的主意:

$computers = $this->Computers->find('all', [
    'conditions' => [
        'last_report_pass' => '0',
        'COUNT(Reports) NOT' => '0'
    ],
    'contain' => [
        'Reports' => [
            'conditions' => [
                'status' => '0'
            ]
        ]
);

我不知道从这里做什么.我可能可以用SQL编写此代码,但是试图坚持使用Cake的ORM查询生成器.预先感谢!

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!

推荐答案

您将需要使用matching其类似于包含,但将按关联的数据进行过滤:

You will need to use matchingits similar to contain, but it will filter by associated data:

会是这样

$query->distinct(['Computers.id'])
    ->matching('Reports', function ($q) {
        return $q->where(['Reports.last_report_pass' => 0]);
    });

重要的是要注意,如果需要显示此表上的某些数据,则还必须contain Reports表.

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.

参考

这篇关于CakePHP查询-基于包含字段的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:34