开发者

How to hasMany without foreign key in CakePHP?

开发者 https://www.devze.com 2023-04-01 04:12 出处:网络
I have two tables, say: TAB1 ---- id tab1_md5 TAB2 ---- id tab2_md5 I would like to create a hasMany relation without foreignKey to be able to use cakephp recursive stuff but don\'t know how to c

I have two tables, say:

TAB1
----
id
tab1_md5


TAB2
----
id
tab2_md5

I would like to create a hasMany relation without foreignKey to be able to use cakephp recursive stuff but don't know how to create the relationship. I've tried with:

var $hasMany = array(
'Tab2' => array(
'className' => 'Tab2',
'foreignKey' => false))

but i don't know what i should specify in conditi开发者_Python百科on

EDIT: the relation is tab1.tab1_md5=tab2.tab2_md5


I don't believe you can do a hasMany relationship without using a foreign key. CakePHP, at that point, has no idea how these tables should be related. Without knowing the relationship it can't do any joins to include the associated table data.


It's not possible. Cake must do a separate query to fetch hasMany data. In that separate query it only uses the primary key of the related model. AFAIK there's currently no way to make it use anything but the primary key. So you'll have to do these queries manually:

$tab1s = $this->Tab1->find('all', array(...));
$tab2s = $this->Tab2->find('all', array(
    'conditions' => array('Tab2.tab2_md5' => Set::extract('/Tab1/tab1_md5', $tab1s))
));

$grouped = array();
foreach ($tab2s as $tab2) {
    $grouped[$tab2['Tab2']['tab2_md5']][] = $tab2;
}
foreach ($tab1s as &$tab1) {
    $tab1['Tab2'] = isset($grouped[$tab1['Tab1']['tab1_md5']]) ? $grouped[$tab1['Tab1']['tab1_md5']] : array();
}

Something along these lines. You could do this automatically in an afterFind callback in the model itself to get the Cake automagic effect.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号