【问题标题】:Use OR conditions on associated model in CakePHP 3在 CakePHP 3 中的关联模型上使用 OR 条件
【发布时间】:2018-12-30 14:51:37
【问题描述】:

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

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

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

【问题讨论】:

    标签: cakephp-3.0 cakephp-3.4


    【解决方案1】:

    如果你遵循蛋糕惯例应该是简单的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 2023-03-16
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多