问题
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'
]);
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...
This is the raw SQL you may want as the reference,
$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:
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 . "%'
]
]);
or using query expressions
$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%")'
]);
});
来源:https://stackoverflow.com/questions/51473939/use-or-conditions-on-associated-model-in-cakephp-3