在CakePHP 3中对关联模型使用OR条件

时间:2018-07-23 07:50:23

标签: cakephp-3.0 cakephp-3.4

我有3个模型,基本模型是工作,而客户,联系人是与工作相关的模型。这是关联。

$this->belongsTo('Customers', [
        'className' => 'Customers',
        'foreignKey' => 'customer_id',
        'joinType' => 'INNER'
    ]);
    $this->belongsTo('Contacts', [
        'className' => 'Contacts',
        'foreignKey' => 'contact_id',
        'joinType' => 'INNER'
    ]);

我想在所有3个表中搜索文本,并返回至少具有其中一个表具有搜索文本的作业记录...我想使用CakePHP的ORM实现此目的...

这是您可能希望用作参考的原始SQL,

$searchText = 'Bikash';
$JobQ->query("SELECT *
                        FROM Jobs
                        LEFT JOIN Customer ON Jobs.CustomerID=Customers.CustomerID
                        LEFT JOIN Contacts ON Jobs.ContactID=Contacts.ContactID
                WHERE ( 
                    Job.JobName LIKE '%" . $searchText . "%' or
            Customer.Name LIKE '%" . $searchText . "%' or
            Contact.FirstName LIKE '%" . $searchText . "%' or
            Contact.Surname LIKE '%" . $searchText . "%');

1 个答案:

答案 0 :(得分:3)

如果您遵循蛋糕惯例,应该简单:

$jobs = $this->Jobs->find()
    ->contain(['Customers', 'Contacts'])
    ->where([
        'OR' => [
            'Jobs.JobName LIKE' => '%" . $searchText . "%',
            'Customers.Name LIKE' =>  '%" . $searchText . "%',
            'Contacts.FirstName LIKE' =>  '%" . $searchText . "%',
            'Contacts.Surname LIKE' =>  '%" . $searchText . "%'
        ]
    ]);

或使用查询表达式

$jobs = $this->Jobs->find()
    ->contain(['Customers', 'Contacts'])
    ->where(function ($exp, $query) {
        return $exp->or_([
            $exp->like('Jobs.JobName', "%$searchText%"),
            $exp->like('Customers.Name, "%$searchText%"),
            $exp->like('Contacts.FirstName, "%$searchText%"),
            $exp->like('Contacts.Surname', "%$searchText%")'
        ]);
    });