Tuesday, July 30, 2013

Re: hasMany / belongsTo not working

On Tue, Jul 30, 2013 at 6:50 AM, WhyNotSmile <sharongilmore78@gmail.com> wrote:
> I have a pretty simple pair of objects, Photo and Album, defined as follows:
>>
>> class Album extends Model {
>> public $name = 'Album';
>>
>> public $hasMany = array(
>> 'Photo' => array(
>> 'className' => 'Photo',
>> 'order' => 'Photo.order ASC'
>> )
>> );
>> }
>
>> class Photo extends Model {
>> public $name = 'Photo';
>> public $belongsTo = array('Album');
>> }
>
>
> I currently have 3 albums, one with 0 photos, one with 1 photo, and one with
> 2 photos. When I do the following in the controller, I expect to get 3
> albums back:
>
>> $albumlist = $this->Album->find('all');
>> debug($albumlist);
>
> But in fact, I get 4 - the one with 2 photos is shown twice. If I had
> another photo, I get the album back 3 times. I'm absolutely stumped as to
> what's causing this, and have a feeling it must be something really stupid
> that I've done. I've set up much more complex models than this in the past,
> with no problems.

Did you inserted the records using those CakePHP models?

Is your database modeled properly?

How the related SQL queries looks like in debug mode?

Check if you get the same information querying the database directly
with something like this (assuming the standard conventions) in your
SGBD query prompt.

SELECT p.*
FROM photos p INNER JOIN albums a
ON (p.album_id=a.id)

Assuming you followed the standard conventions and just for a debugging
purpose, try to simplify your associations and redo the tests.

// Album
public $hasMany = 'Photo';

// Photo
public $belongsTo = 'Album';

Hope it helps.

MARCELO DE FREITAS ANDRADE
https://mailstrom.co/mfandrade

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.

No comments: