1

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 . "%');
bikash.bilz
  • 821
  • 1
  • 13
  • 33

1 Answers1

3

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%")'
        ]);
    });
Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
arilia
  • 9,373
  • 2
  • 20
  • 44