Never show some entries in CakePHP

I would like to return some entries from my database (for example, user roles). And I usually use the find () function, findAll (), etc., and I should always write “conditions” like this: do not show the admin (name role ! = Admin). My question is: how can I in RoleModel installed for all functions will return with these conditions.

Sorry for the English!

Bye!

+3
source share
2 answers

Use a callback beforeFind()( http://book.cakephp.org/view/680/beforeFind ) for this kind of thing. Here I use from time to time, which ensures that 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;
}

, , - . , , , , . , .

+4

, hasMany.

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

, :

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

Source: https://habr.com/ru/post/1734446/


All Articles