Wednesday, July 29, 2009

Re: CakePHP array structure on a HABTM

$this->Country->Behaviors->attach('Containable');

$this->Country->find('all', array('contain' => array(
'CountriesNetwork' => array(
'fields' => array('CountriesNetwork.id',
'CountriesNetwork.network_id'),
)
)));

http://book.cakephp.org/view/474/Containable

On Jul 29, 7:32 am, Chris <carpetf...@googlemail.com> wrote:
> I have two tables: countries and networks, linked via a HABTM using
> countriesNetwork lookup table.
>
> I want to perform a query ob the countries table to get all
> Country.countryName rows, but each country needs to  have an array of
> CountriesNetwork.network_id too. Something like this:
>
> I have two tables linked via a HABTM. countries & networks. They are
> linked together by the countries_networks lookup table.
>
> I need to get all of the countries and all of the associated network
> ids for each corresponding country. I don't need to go as far as
> getting the network names, simply getting the ids from the lookup
> table will suffice.
>
> If I do a find(all) it gives me an array of countries but not in the
> structure that I need. I need to return something link this, but I
> only need Country.countryName and CountriesNetwork.network_id:
>
> Array
> (
>     [0] => Array
>         (
>             [Country] => Array
>                 (
>                     [countryName] => France
>                 )
>             [CountriesNetwork] => Array
>                 (
>                     [0] => Array
>                                (
>                                     [id] => 1
>                                     [network_id] => 1
>                                 )
>                     [1] => Array
>                                (
>                                     [id] => 2
>                                     [network_id] => 7
>                                 )
>                  )
>          )
> )
>
> I've been struggling with find all and I've tried a custom query using
> a join, but it results in lots of duplicate countries. I just want the
> country name along with an array of network_id's. ( I could go as far
> as getting the network name from the network table if its easier.)
>
> I've even tried using unbind and bind to change my associations, but I
> haven't had much look there:http://pastebin.com/m1cca9e77
>
> Can someone possibly help me on this? I know it will be one of those
> 'aah i see' moments. Many thanks.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
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?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: