views:

61

answers:

2

Hi, 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). My question is, how I can in RoleModel set for all function will be return with this conditions.

Sorry for english!

Bye!

+3  A: 

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.

Rob Wilkerson
array_key_exists($conditions, 'active') should by array_key_exists('active', $conditions), but still doesn't work. I set conditions but there is no diffrent
kicaj
okey, works perfect!fix: return true to return $queryData
kicaj
Glad it worked for you. Apologies for the inaccuracies. I'm not on a box where I could look up old projects.
Rob Wilkerson
+2  A: 

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)));
KienPham.com