filter conditions from an association

眉间皱痕 提交于 2019-12-08 21:42:30
$tmpConditions['OR'][] = array('staffgroups.groupname LIKE' => "%$group%");

Is not following the CakePHP conventions. It should be:

$tmpConditions['OR'][] = array('StaffGroup.group_name LIKE' => "%$group%");

Model and Database conventions:

Models:

Model classnames are singular and CamelCased. Person, BigPerson, and ReallyBigPerson are all examples of conventional model names.

Database tables:

Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.

Database fields:

Field names with two or more words are underscored like, first_name.

Following these conventions, you should have a table called staff_groups which contains a field called group_name. The associated model would be named StaffGroup.

You cannot do that "out of the box", due to the HABTM association. You have to do it by hand.

First you need to get the StaffGroup.id(s) you are looking for

$group_ids = $this->Staff->StaffGroup->field('id', array('groupname LIKE' => '%$group%') );

Then unbind the HABTM association, and then bind the join table as hasMany association

$this->Staff->UnbindModel( array('hasAndBelongsToMany' => array('StaffGroup')) );
$this->Staff->bindModel(array('hasMany' => array('StaffStaffGroup')));

You can now perform your search

$this->Staff->StaffStaffGroup->find(
    'all', 
    array(
        'conditions' => array(
            'StaffStaffGroup.staff_group_id' => $group_ids,
            'Staff.isActive =' => "1",
            'Staff.lastname LIKE' => "%$name%",
        )
    )
);

In your $tmpConditions array the you should have the following format:

$tmpConditions = array(
       "AND" => array('Staff.isActive =' => "1"),
       "OR"  => array(
                'Staff.lastname LIKE' => "%$name%",
                'Staffgroup.groupname LIKE' => "%$group%"
       )
);

I assume that you have a table named staffgroups and that it actually contains the field groupname.

Also the line

$this->Staff->recursive = 1;

should be

$this->paginate = array(
      ...
      'recursive' => 1
);

I believe that this should do the job...

Just change staffgroups to Staffgroup. Naming conventions for models vs. tables means db table my_tables will be named model MyTable. See http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!