所有查询的CakePHP 3.x默认模型条件

时间:2019-04-19 17:47:45

标签: cakephp cakephp-3.x

我发现了CakePHP 2.x的多种解决方案(例如,Defining global conditions in Model)和CakePHP 3.x Controller查询的解决方案: $this->Articles->find('all', ['conditions' => ['domain =' => $this->request->host()]]);,但对于Models中的CakePHP 3.x全局查询条件则无效。当我使用

function beforeFind($event, $queryData, $options) {
    $queryData['conditions'][]['NOT'][$this->alias . '.parent_id'] = null;
    return $queryData;
}

我收到错误Cannot use object of type Cake\ORM\Query as array

1 个答案:

答案 0 :(得分:0)

好吧,经过几个小时的搜索,我找到了一个非常简单的解决方案:

public function beforeFind($event, $query, $options) {  
      $query->where(['field_name' => 'field_value']);
      return $query;
}

或在initialize()内部:

class MyClassTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('table_name');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');    

        $this->belongsTo('OtherClass', [
            'foreignKey' => 'class_id',
            'joinType' => 'INNER'
        ])->setConditions(['class_name' => 'any_value']);

    }
}