Use OR conditions on associated model in CakePHP 3

别来无恙 提交于 2019-12-13 01:53:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!