开发者

Never display some records in CakePHP

I would like return some records from my base (eg. users roles) And I use usually function find(), findAll(), etc., and I always must write 'conditions' with like this: not display role admin (name!=admin). M开发者_如何学Goy question is, how I can in RoleModel set for all function will be return with this conditions.

Sorry for english!

Bye!


Use the beforeFind() (http://book.cakephp.org/view/680/beforeFind) callback for this kind of thing. Here's one I use from time to time that ensures only active records are returned:

function beforeFind( $queryData )
{
  $conditions = $queryData['conditions'];

  if( !is_array( $conditions ) ) {
    if( !$conditions ) {
      $conditions = array();
    } 
    else {
      $conditions = array( $conditions );
    }
  }

  if( !array_key_exists( $conditions, 'active' ) && !isset( $conditions[$this->alias . '.active'] ) ) {
    $conditions[$this->alias . '.active'] = 1;
  }

  return true;
}

That's a bit off the cuff, so the syntax may not be exact, but it should give you something to start with. I think everything's in order except, perhaps, the argument order in a few function calls. Anyway, it should be close.


I think a better solution would be setting the condition in your hasMany relationship.

// User.php Model:
var $hasMany = array('Role' => array('conditions' => array('name <>' => admin)));

and vice versa, you can do it for your Role model:

// Role.php Model:
var $belongsTo = array('User' => array('conditions' => array('User.name <>' => admin)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜