【问题标题】:cakephp 2.x beforeFind associated modelscakephp 2.x beforeFind 关联模型
【发布时间】:2014-03-12 19:48:37
【问题描述】:

如何将 beforeFind() 条件传播到关联模型中?

以 School、Course 和 Term 为例(应该是 Class,但这个词在 php 中是保留的),这是 Course 模型上使用的代码:

/**
 * beforeFind method
 *
 * Filters by the school (based on the url)
 * @param  array  $query The find query
 * @return array  $query The query with the added condition
 */
public function beforeFind($query = array()) {
    parent::beforeFind($query);
    $query['conditions'] = (is_array($query['conditions'])) ? $query['conditions'] : array();
    $this->School->id = CakeSession::read('School');
    $conditions = array(get_class($this).'.school_id' => $this->School->id);
    $query['conditions'] = array_merge($query['conditions'], $conditions);
    return $query;
}

当我获取课程时,条件适用:

$this->Course->contain = array('School');
$this->Course->find('all');

这会根据会话返回当前学校的所有课程。 当我取课时,学校条件不适用:

$this->Term->contain = array('Course');
$this->Term->find('all');

它返回所有条款,包括所有课程,没有课程模型上的 beforeFind 条件。 是否可以在传播到其子模型的父模型上添加 beforeFind 条件,而不必在每个子模型上编写 beforeFind 代码?

【问题讨论】:

    标签: php cakephp before-filter


    【解决方案1】:

    不幸的是,我认为这在 Cake 2.x 中是不可能的。如果您查看this ticket from Github,使用关联模型中的beforeFind 的问题在Cake 3.0(在页面底部)中已修复,但对于旧版本没有解决方案,除了手动更改核心文件。

    【讨论】:

      【解决方案2】:

      正如已经回答的那样,在 Cake 2.x 中使用 beforeFind() 是不可能的。 但是,您可以在 afterFind() 中过滤项目:

      public function afterFind($results = array(), $primary = false) {
          foreach($results as $x=>$items) {
              foreach($items as $model=>$item) {
                  if( isset($item['was_deleted']) AND !empty($item['was_deleted']) ) {
                      unset($results[$x]);
                  }
              }
          }
      
          return $results;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多