filter HABTM-associated model with conditions

谁都会走 提交于 2019-12-05 10:04:44

You cannot use the Containable behavior for this. Checkout the sql dump, you will see that the query is done.

I would do it in two steps

From StaffStaffgroup get the staff ids that belongs to the group you want

$staff_ids = $this->Staff->StaffStaffgroup->find(
    'all', 
    array(
        'conditions' => array('StaffStaffgroup.staffgroup_id' => $group_id, ),
        'recursive' => -1,
        'fields' => array('StaffStaffgroup.staff_id'),
    )
);

Then get all staff using the previous result

$staffs = $this->Staff->find(
    'all', 
    array(
        'conditions' => array(
            'Staff.id' => $staff_ids, 
            'Staff.isActive =' => "1",
            'Staff.last_name LIKE' => "%$name%",
        ),
    )
);

You should look into the Containable behaviour.

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

This will allow you to query your Staff model and contain your StaffStaffgroup model, giving you the array organised in the way you want.

I realize this question was asked a long time ago but my comment could still help someone else finding this post.

I created a behavior that creates the proper joins to the HABTM association behind the scenes making you able to use conditions on the HABTM-model.

Example

The model:

<?php
class Product extends AppModel {

    public $actsAs = array(
        'FilterHabtm.FilterHabtm',
        'Containable' // If you use containable it's very important to load it AFTER FilterHabtm
    );

    public $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'product_id',
            'associationForeignKey' => 'category_id',
            'with' => 'CategoryProduct'
        )
    );

}

The controller:

(The following is made possible by the behavior)

<?php
class ProductsController extends AppController {

    public $name = 'Products';

    public function index($categoryId = null) {
        $products = $this->Product->find('all', array(
            'conditions' => array(
                'Category.id' => $categoryId // Filter by HABTM conditions
            )
        ));
    }

}

Please see this url for download and complete usage instructions: https://github.com/biesbjerg/FilterHabtm

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