1

我有一个搜索功能,非常适合员工,所以我可以按姓名搜索。现在,我想通过 staffgroup.groupname 过滤员工,但不幸的是我收到了这个错误:

Column not found: 1054 Unknown column 'staffgroups.groupname' in 'where clause'

我有以下表格布局

  • 员工(一个人可以属于多个组)
  • staff_staffgroups(HABTM 链接表)
  • staffgroups(有组名)

我使用的条件如下:

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

$this->Staff->recursive = 1;
$this->paginate = array('conditions' =>  $tmpConditions );
$this->set('staffs', $this->paginate());

我无法让它工作,尽管我认为条件设置正确。

干杯

4

4 回答 4

1

由于 HABTM 协会,您不能“开箱即用”地做到这一点。你必须手工完成。

首先你需要得到你正在寻找的 StaffGroup.id(s)

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

然后解绑定HABTM关联,然后将join表绑定为hasMany关联

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

您现在可以执行搜索

$this->Staff->StaffStaffGroup->find(
    'all', 
    array(
        'conditions' => array(
            'StaffStaffGroup.staff_group_id' => $group_ids,
            'Staff.isActive =' => "1",
            'Staff.lastname LIKE' => "%$name%",
        )
    )
);
于 2013-01-29T07:50:23.893 回答
1
$tmpConditions['OR'][] = array('staffgroups.groupname LIKE' => "%$group%");

不遵循CakePHP 约定。它应该是:

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

模型和数据库约定

楷模:

模型类名是单数和 CamelCased。Person、BigPerson 和ReallyBigPerson 都是常规模型名称的示例。

数据库表:

对应于 CakePHP 模型的表名是复数形式并带有下划线。上述模型的基础表分别是 people、big_people 和 real_big_people。

数据库字段:

包含两个或多个单词的字段名称带有下划线,例如 first_name。

按照这些约定,您应该有一个名为的表staff_groups,其中包含一个名为 的字段group_name。关联的模型将命名为StaffGroup.

于 2013-01-28T13:24:34.823 回答
0

只需更改staffgroupsStaffgroup. 模型与表的命名约定意味着 db 表my_tables将被命名为 model MyTable。请参阅http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions

于 2013-01-28T15:48:27.943 回答
0

在您的$tmpConditions数组中,您应该具有以下格式:

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

我假设您有一个名为的表staffgroups,并且它实际上包含字段groupname

还有线

$this->Staff->recursive = 1;

应该

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

我相信这应该做的工作......

于 2013-01-28T14:41:45.137 回答