【问题标题】:Condition in read() function CakePHPread() 函数中的条件 CakePHP
【发布时间】:2011-09-22 12:24:10
【问题描述】:

在 CakePHP 函数 edit 我使用 read() 函数作为:

$this->data = $this->Article->read(null, $id);

它带来了$id的所有字段。现在,我正在尝试调整以在read() 中再提供一个条件,以便仅当用户登录与其相关时才能获取文章。

例如:

 $this->Article->user_id = $user_id;
 $this->Article->id = $id;
 $this->Article->read();

显然它想要工作,因为read() 只带来数据 w.r.t. $id(主键)。

我的问题:

  1. 有没有办法调整条件超过$id 的读取功能?因为如果它有效,它只需要在我的所有控制器中添加一行?
  2. 或者我必须使用 find() 函数的长代码来获取是唯一的选择吗?

任何最好的解决方案都将是可观的。

【问题讨论】:

  • 你可以尝试使用magick函数:$this->Article->findByUserId($user_id);

标签: php cakephp cakephp-model


【解决方案1】:

如果你真的必须这样做,你可以使用 OOP 技术来覆盖核心方法的工作方式。

只需将 Model::read() 方法复制到您的 AppModel 类并进行必要的更改。

【讨论】:

    【解决方案2】:

    如果你想有条件地进行搜索,你必须使用find()。另一种选择是仅在条件成立时才读取数据:

    $this->Article->id = $id;
    if( $this->Article->field( 'user_id' ) == $user_id ) {
        $this->Article->read();
    }
    

    read() 自动填充 $this->data。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多