从hasMany表关系中检索数据

时间:2013-04-12 00:29:56

标签: cakephp cakephp-2.1 has-many

我有3张桌子:

证书,请求和请求

请求hasMany Requestc。 Requestc使用certificates_requests表,并有id request_idcertificate_id coloumns。

我正在尝试从Request表中检索数据,并尝试检索与该请求相关联的证书的名称。

我在没有成功的情况下尝试这个:

$options['joins'] = array (
                    array( 'table' => 'certificates_requests',
                            'alias' => 'Requestc',
                            'type' => 'left',
                            'conditions' => array('Certificate.id = Requestc.certificate_id')

                    )
    );
$certidoes = $this->Request->find('all', $options);

我的模特:

class Certificate extends AppModel {

public $name = 'Certificate';}




class Request extends AppModel {

public $name = 'Request';

public $hasMany = array(
    'Requestc' => array(
        'foreignKey'    => 'request_id'
    )
); }



class Requestc extends AppModel {

public $name = 'Requestc';
public $belongsTo = 'Request';
public $useTable = 'certificates_requests'; }

1 个答案:

答案 0 :(得分:1)

这看起来像是我的HABTM关系。

可包含的行为将解决您的问题。 Read More Here

<?php

// Request.php // Model
var $actsAs = array('Containable');
var $hasAndBelongsToMany = array(
    'Certificate' => array(
        'className' => 'Certificate',
        'joinTable' => 'certificates_requests',
        'foreignKey' => 'request_id',
        'associationForeignKey' => 'certificate_id'
    )
);

// Certificate.php // Model
var $actsAs = array('Containable');
var $hasAndBelongsToMany = array(
    'Request' => array(
        'className' => 'Request',
        'joinTable' => 'certificates_requests',
        'foreignKey' => 'certificate_id',
        'associationForeignKey' => 'request_id'
    )
);

// RequestsController.php
$this->Request->contain(array(
    'Certificate' => array(
        'fields' => array('id', 'name')
    )
));

$request = $this->Request->read(null, <requestIdHere>);
// $request = array(
//     'Request' => array(
//          '<requestData>',
//          ...
//     ),
//     'Certificate' => array(
//          [0] => array(
//              'id'     => <idGoesHere>,
//              'name'   => "<nameGoesHere>'
//          ),
//          [1] => array(
//              'id'     => <idGoesHere>,
//              'name'   => "<nameGoesHere>'
//          ),
//          [2] => array(
//              'id'     => <idGoesHere>,
//              'name'   => "<nameGoesHere>'
//          ),
//     )
// )
?>

如果这可以解决您的问题,请告诉我。 :)

-DREW