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

Use OR conditions on associated model in CakePHP 3

我有 3 个模型,基本模型是 JobsCustomers, Contacts 是与工作相关的模型。这里是协会。

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

我想在所有 3 个表中搜索一个文本 并且 return 至少在任何一个表中具有搜索文本的工作记录.. . 我想用 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 . "%');

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

$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%")'
        ]);
    });