CakePHP - 将两个表合并为一个

时间:2014-06-04 15:03:07

标签: php cakephp

我有一个问题,我有两个型号,他们是“Clientes”和“Residencias”(它是葡萄牙语)。

我的问题是..我试图将这两个链接在一个...我用“cliente_id”和“residencia_id”创建了一个新表......

使用关系$ belongsTo的输出就像那样...

array(
    0 => array(
        'bd' => array(
            'id' => 1,
            'cliente_id' => null,
            'residencia_id' => 2
        ),
        'Cliente' => array(),
        'Residencia' => array(
            'id' => 2
            'nome'  => 'aaa',
            'telefone'  => '333'
        )
    ),
    1 => array(
        'bd' => array(
            'id' => 2,
            'cliente_id' => 1,
            'residencia_id' null
        ),
        'Cliente' => array(
            'id' => 1,
            'nome' => 'bbb',
            'telefone' => '666'
        ),
        'Residencia' => array()
    )
)

得到它??

我想这样做:

array(
    0 => array(
        'bd' => array(
            'id' => 1,
            'cliente_id' => null,
            'residencia_id' => 2
        ),
        'Result' => array(
            'id' => 2
            'nome'  => 'aaa',
            'telefone'  => '333'
        )
    ),
    1 => array(
        'bd' => array(
            'id' => 2,
            'cliente_id' => 1,
            'residencia_id' null
        ),
        'Result' => array(
            'id' => 1,
            'nome' => 'bbb',
            'telefone' => '666'
        )
    )
)

得到它?我想在模型和Paginate中做到这一点......有人可以帮助我吗?我没有找到答案......我不知道怎么......

谢谢

1 个答案:

答案 0 :(得分:0)

您可以在要查询的模型中创建一个afterFind回调,它将修改结果并以您想要的格式返回。它可能看起来像这样:

    public function afterFind($results, $primary = false) {
    if ($this->findQueryType == 'count' || !$primary) {
        return parent::afterFind($results, $primary);
    }

    foreach ($results as $k => $result) {
        if (!empty($result['Cliente'])) {
            $id = $result['Cliente']['id'];
            $nome = $result['Cliente']['nome'];
            $telefone = $result['Cliente']['telefone'];
        } else if (!empty($result['Residencia'])) {
            $id = $result['Residencia']['id'];
            $nome = $result['Residencia']['nome'];
            $telefone = $result['Residencia']['telefone'];
        }

        $results[$k]['Result'] = array(
            'id' => $id,
            'nome' => $nome,
            'telefone' => $telefone
        );
        unset($results[$k]['Cliente']);
        unset($results[$k]['Residencia']);
        continue;
    }

    return $results;
}