在CakePHP 3中对关联模型使用OR条件 [英] Use OR conditions on associated model in CakePHP 3
本文介绍了在CakePHP 3中对关联模型使用OR条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个模型,基本模型是工作,而客户,联系人是与工作相关的模型。这是关联。
I have 3 models, the base model is Jobs and Customers, Contacts are the models associated with jobs. Here is the association.
$this->belongsTo('Customers', [
'className' => 'Customers',
'foreignKey' => 'customer_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Contacts', [
'className' => 'Contacts',
'foreignKey' => 'contact_id',
'joinType' => 'INNER'
]);
我想在所有3个表中搜索文本并返回作业记录中至少有一个表具有搜索文本...我想使用CakePHP的ORM实现此目标...
I want to search a text in all the 3 tables and return the job records which are having the search text at least any one of the tables... I want to achieve this using CakePHP's 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 . "%');
推荐答案
如果您遵循蛋糕惯例,应该简单:
If you are following cake conventions should be simply:
$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%")'
]);
});
这篇关于在CakePHP 3中对关联模型使用OR条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文