【问题标题】:Searching data from associated models in CakePHP在 CakePHP 中从关联模型中搜索数据
【发布时间】:2014-05-15 11:32:22
【问题描述】:

我使用的是 CakePHP 2.3.6。在我的项目中,我必须使用一些值/数据/参数来搜索用户,这些值/数据/参数在几个表中,并且这些表是关联的。

关联是:

在模型User.php

public $hasMany=array('Education'=>array(
                        'className'=>'Education
                        'foreignKey'=>'user_id'
                  ),
                  'Experience'=>array(
                        'className'=>'Experience',
                        'foreignKey'=>'user_id'
                  ),
                  'Employment'=>array(
                        'className'=>'Employment',
                        'foreignKey'=>'user_id'
                  ),
                  'ProfessionalQualification'=>array(
                        'className'=>'ProfessionalQualification',
                        'foreignKey'=>'user_id'
                  )
)

在模型Education.php

public $belongsTo=array('User'=>array(
                        'className'=>'User',
                        'foreignKey'=>'user_id'
                    )
)

在模型Experience.php

public $belongsTo=array('User'=>array(
                        'className'=>'User',
                        'foreignKey'=>'user_id'
                    )
)

在模型Employment.php

public $belongsTo=array('User'=>array(
                            'className'=>'User',
                            'foreignKey'=>'user_id'
                        )
)

在模型 ProfessionalQualification.php 中:

public $belongsTo=array('User'=>array(
                        'className'=>'User',
                        'foreignKey'=>'user_id'
                    )
)

现在,在搜索表单 (View/Users/search.ctp) 中:

echo $this->Form->create('User');
echo $this->Form->input('name',array('type'=>'text'));
echo $this->Form->input('username',array('type'=>'text'));
echo $this->Form->input('address',array('type'=>'textarea'));
echo $this->Form->input('phone',array('type'=>'tel'));
echo $this->Form->input('degree',array('type'=>'text'));
echo $this->Form->input('passing_year',array('type'=>'text'));
echo $this->Form->input('title',array('type'=>'text'));
echo $this->Form->input('title.description',array('type'=>'textarea'));
echo $this->Form->input('company',array('type'=>'text'));
echo $this->Form->input('company.description',array('type'=>'textarea'));
echo $this->Form->input('certificate',array('type'=>'text'));
echo $this->Form->input('certificate.description',array('type'=>'textarea'));
echo $this->Form->submit('Search');
echo $this->Form->end();

UsersController.php 控制器中:

public function search(){
    $this->set('title_for_layout','Search User');

    if($this->request->is('post')){
       $conditions=array();
       $data=$this->request->data;
   if(!empty($data['name']))
      $conditions['name']="%".$data['name']."%";
   if(!empty($data['username']))
      $conditions['username']=$data['username'];
   if(!empty($data['address']))
      $conditions['address']='%'.$data['address'].'%';
   if(!empty($data['phone']))
      $conditions['phone']=$data['phone'];
   if(!empty($data['degree']))
      $conditions['degree']="%".$data['degree']."%";
       .
       .
       .
   if(!empty($data)){
      $users=$this->User->find('all',array('conditions'=>$conditions));
          if(!empty($users)){
             $this->Session->setFlash("Searching Users Successful");
             $this->set('users',$users);
          }else
             $this->Session->setFlash("No user found");
   }else
      $this->Session->setFlash("You didn't give any info to search for");
    }
}

我认为它会从数组中的所有关联表中检索我正在寻找的所有数据。但是,它给出了一个错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'degree' in 'where clause'

SQL Query: SELECT `User`.`id`, `User`.`name`, `User`.`username`, `User`.`phone`, `User`.`address`, `User`.`created`, `User`.`modified` FROM `db_name`.`users` AS `User` WHERE `degree` = 'M.Sc.'

这里,“学位”来自“教育”表。

然后,我使用了ContainableBehavior。在User.php 模型中:

public $actsAs=array('Containable');

UsersController.php

$this->User->find('all',array('contain'=>array('Education'=>array(
                                                'conditions'=>array('Education.institution ='=>"Institute 1")
                                               ),
                                               'Employment'=>array(
                                                'conditions'=>array('Employment.employer ='=>"Employer 1")
                                               ),
                                               'ProfessionalQualification'=>array(
                                'conditions'=>array('ProfessionalQualification.certificate ='=>"Certificate 1")
                                               ),
                                               'Experience'=>array(
                                'conditions'=>array('Experience.title ='=>"Title 1")
                                               )
                         )
                 )
);

当我使用它时,结果数组是:

array(
(int) 0 => array(
    'User' => array(
        'name' => 'Name 3',
        'email' => 'user3@email.com',
        'mobile' => '9325028505',
        'id' => '4'
    ),
    'Education' => array(),
    'Employment' => array(),
    'ProfessionalQualification' => array(),
    'Experience' => array()
),
(int) 1 => array(
    'User' => array(
        'name' => 'Name 2',
        'email' => 'user2@email.com',
        'mobile' => '9082730572',
        'id' => '3'
    ),
    'Education' => array(),
    'Employment' => array(),
    'ProfessionalQualification' => array(),
    'Experience' => array()
),
(int) 2 => array(
    'User' => array(
        'name' => 'Name 1',
        'email' => 'user1@email.com',
        'mobile' => '715414918934',
        'id' => '2'
    ),
    'Education' => array(
        (int) 0 => array(
            'id' => '1',
            'applicant_id' => '2',
            'level' => 'Secondary',
            'degree_title' => 'S.S.C',
            'passing_year' => '2009',
            'institution' => 'Institute 1',
            'result' => '4',
            'major' => 'Science',
            'created' => '2014-05-18 16:48:08',
            'modified' => '2014-05-18 17:20:12'
        )
    ),
    'Employment' => array(
        (int) 0 => array(
            'id' => '1',
            'applicant_id' => '2',
            'employer' => 'Employer 1',
            'position_held' => 'Position 1',
            'industry' => 'Industry 1',
            'department' => 'Department 1',
            'major_responsibilities' => 'Responsibilities 1',
            'job_location' => 'Local',
            'key_achievement' => 'Achievements 1',
            'served_from' => '2005-03-12',
            'served_till' => '2007-11-26',
            'created' => '2014-05-18 16:48:08',
            'modified' => '2014-05-18 17:20:12'
        )
    ),
    'ProfessionalQualification' => array(
        (int) 0 => array(
            'id' => '1',
            'applicant_id' => '2',
            'name_of_certificate' => 'Certificate 1',
            'institute' => 'Institute 1',
            'from' => '2011-10-11',
            'to' => '2012-09-11',
            'location' => 'Local Ins.',
            'created' => '2014-05-18 16:48:08',
            'modified' => '2014-05-18 17:20:12'
        )
    ),
    'Experience' => array(
        (int) 0 => array(
            'id' => '1',
            'applicant_id' => '2',
            'title' => 'Title 1',
            'institute' => 'Institute 1',
            'training_year' => '2013',
            'location' => 'Local Ins.',
            'created' => '2014-05-18 16:48:08',
            'modified' => '2014-05-18 17:20:12'
        )
    )
),
(int) 3 => array(
    'User' => array(
        'name' => 'Name 4',
        'email' => 'user4@email.com',
        'mobile' => '9082730572',
        'id' => '5'
    ),
    'Education' => array(),
    'Employment' => array(),
    'ProfessionalQualification' => array(),
    'Experience' => array()
)
)

请注意,我只需要 2 号。数组,没有别的,但它给了我所有不相关的数据。

你能告诉我问题出在哪里吗?我应该怎么办 ?我想,我必须在特定字段上明确给出表格中的表名,例如:ModelName.0.field。你怎么看?

【问题讨论】:

  • 附加行为并使用字段指定模型名称,它应该可以工作。
  • 这个答案可能对你有帮助stackoverflow.com/questions/13563435/…
  • 不,对不起,这也帮不了我。顺便说一句,谢谢:)。 @BharatMaheshwari
  • 我刚刚尝试使用“可包含”行为,但我没有得到我想要的格式的数据。它返回所有数据,而不是特定数据。我已经用结果更新了我的问题。可以再看一遍吗?谢谢@SougataBose
  • 如果您想要特定数据,请尝试提及可包含行为的字段。

标签: cakephp search model-associations


【解决方案1】:

试试这个

  public function global_search() {
        $condition = array(
            'User.role' => array('U', 'P'),
            'User.user_status' => array('active', 'lead', 'inactive')
        );
        if ($this->request->is('post') || $this->request->is('put')) {


            $or = array(
                'PersonalInformation.first_name' => $this->request->data['User']['first_name'],
                'PersonalInformation.last_name' => $this->request->data['User']['last_name'],
                'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'],
                'PersonalInformation.dob' => $this->request->data['User']['dob'],
                'User.email' => $this->request->data['User']['email'],
            );
            //==========This Function allow remove blank element from array=========//

            $or = array_filter($or);

            //=====End============//

            $condition = array(
                'User.role' => array('U', 'P'),
                'User.user_status' => array('active', 'lead', 'inactive'),
                'OR' => $or
            );

            $data = $this->User->find('first', array(
                'conditions' => $condition)
            );
            // pr($data); exit;
            $this->set('allusers', $data);
        }

        $data = $this->User->find('all', array(
            'conditions' => $condition)
        );
        //pr($data); exit;
        $this->set('allusers', $data);
        $this->layout = 'admin';
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多