【问题标题】:CakePHP 3.x - How to filter one association by fields of another association?CakePHP 3.x - 如何通过另一个关联的字段过滤一个关联?
【发布时间】:2017-12-24 15:54:48
【问题描述】:

当 - 就像在手册中一样 - 可以过滤给定的变量。

$username = 'markstory';
$query = $articles->find()->matching('Comments.Users', function ($q) use ($username) {
    return $q->where(['username' => $username]);
});

如何过滤来自另一个包含值的值? 我认为下面的例子是可能的。但事实并非如此。

$query = $articles->find()->contain('Names')->matching('Comments.Users', function ($q) use ($username) {
    return $q->where(['username' => Names.username]);
});

【问题讨论】:

    标签: mysql cakephp associations cakephp-3.0 contain


    【解决方案1】:

    仅适用于使用join 策略的hasOnebelongsTo 关联,否则该表将不会包含在主查询中。

    Query::contain()Query::matching() 但是不能很好地一起使用,因为它们以固定的顺序出现,即 matching 连接将放置在 contain 连接之前,这使得通过 Query::matching() 回调使用条件是不可能的.您可以改用Query::leftJoinWith()Query::innerJoinWith(),这会尊重方法调用的顺序,或者将条件添加到主查询中。

    您的字段比较是无效的 PHP,但即使正确引用也不起作用,您必须将原始 SQL sn-p 作为单个值传递,或者最好通过表达式构建它,例如使用QueryExpression::equalFields() 方法。

    $query = $articles
        ->find()
        ->innerJoinWith('Names')
        ->matching('Comments.Users', function (\Cake\ORM\Query $q) use ($username) {
            return $q->where(function (\Cake\Database\Expression\QueryExpression $exp) {
                return $exp->equalFields('Users.username', 'Names.username');
            });
        });
    
    // only works in case `Names` is a `hasOne` or `belongsTo` association
    $query = $articles
        ->find()
        ->contain('Names')
        ->matching('Comments.Users')
        ->where(function (\Cake\Database\Expression\QueryExpression $exp) {
            return $exp->equalFields('Users.username', 'Names.username');
        });
    

    另见

    【讨论】:

      猜你喜欢
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多