如何使用自定义连接cakephp2获取模型的关联数据

时间:2017-07-28 10:30:21

标签: cakephp cakephp-2.0

我正在使用cakephp2并试图加入两个这样的表:

$employee=$this -> Employee ->find ('all',array(
'joins'=>array( 
array('table' => 'employee_histories', 'alias' => 'eh', 'type' => 'LEFT', 'foreignKey' => false, 
'conditions' => array('eh.emp_id= Employee.emp_id'))
),
'fields'=>'Employee.*,eh.*',
)); 

在EmployeeHistory模型中,与表employee_designations存在关联,如下所示:

public $belongsTo = array(

        'EmployeeDesignation' => array(
            'className' => 'EmployeeDesignation',
            'foreignKey' => '',
            'conditions' => 'EmployeeDesignation.designation_id=EmployeeHistory.designation_id',
            'fields' => '',
            'order' => ''
        ),
);

现在可以在$ employee数组中获得EmployeeDesignation结果。

1 个答案:

答案 0 :(得分:0)

您可以通过向joins数组中添加另一个数组来加入$employee= $this->Employee->find('all', array( 'joins'=>array( array( 'table' => 'employee_histories', 'alias' => 'eh', 'type' => 'LEFT', 'foreignKey' => false, 'conditions' => array( 'eh.emp_id= Employee.emp_id' ) ), // array joining the employee designations table array( 'table' => 'employee_designations', 'alias' => 'ed', 'type' => 'LEFT', 'conditions' => array( 'eh.designation_id = ed.designation_id' ) ) ), 'fields'=>'Employee.*, eh.*, ed.*', // include ed fields )); 表。像这样:

function str_replace_links($subject, &$count) {
    //match the first part of the link http://www.example.com{/slug}
    $regex = '/(https:\/\/www.example.com)(\/[a-zA-Z_0-9\-]*)*';
    //check for the trailing '/' or if it is a file
    $regex .= '([^(\/|\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.torrent|\.ttf|\.woff|\.svg|\.eot|\.woff2)])';
    //finish ooff regex
    $regex .= '/i';
    $i; // counter for # changed
    $content = preg_replace($regex, '$1$2/', $subject, 1, $i);
    $count += $i;
    return $content;
}