Wednesday, December 28, 2011

How to "custom belongsto" in CakePHP 2?

HI i'm working with a external database (RADIUS) that follows the next
structure:

CREATE TABLE IF NOT EXISTS `radpostauth` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`pass` varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`reply` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`authdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
AUTO_INCREMENT=19082 ;

and in my app i have another table that follows the CakePHP
conventions

CREATE TABLE IF NOT EXISTS `wdevices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`wcontract_id` int(11) NOT NULL,
`device_mac` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci
NOT NULL,
`wdevices_model_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

What work ok with associations (ie: Wcontract, Wdevice) but i'm trying
to make an belongsto association where:

radpostauth.username = wdevices.device_mac

Currently it's works if i do a hasMany association:

class Radpostauth extends AppModel {
public $useDbConfig = 'radius';
var $name = 'Radpostauth';
public $useTable = 'radpostauth';


var $hasMany = array(
'Wdevice' => array(
'className' => 'Wdevice',
'foreignKey' => false,
'finderQuery' => ' SELECT Wdevice.*
FROM radpostauth, wdevices AS Wdevice
WHERE radpostauth.id={$__cakeID__$}
AND Wdevice.device_mac = radpostauth.username
ORDER BY Wdevice.id DESC
LIMIT 0, 30;'

)
);
}

---

Sample return:

Array
(
[Radpostauth] => Array
(
[id] => 19061
[username] => 00:11:22:33:44:55
[pass] =>
[reply] => Access-Accept
[authdate] => 2011-12-28 12:57:12
)

[Wdevice] => Array
(
[0] => Array
(
[id] => 1
[...]


But it's not the best way to do it because a radpostauth will be have
always just one Wdevice associated so i would like to know if there
are some way to do this kind of association with belongsTo, hasOne,
etc..

Thanks : )

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.


To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: