Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions /

belongs_many_many to many_many accessor


Reply


6 Posts   4030 Views

Avatar
jahbini

Community Member, 13 Posts

16 April 2009 at 1:47pm

Edited: 17/04/2009 2:21am

I need to access all words belonging to sentences, and ALSO list all sentences that contain a given word. (this is not the real example, but it's as close as I can come and explain easily). A has many_many and belongs_many_many seems the right choice, but the accessor does not work from the 'belongs_many_many side. It seems like it should be easy, but I must be missing something. Any help?

class Sentence extends DataObject {
....
static $many_many = array( 'Words' => 'Word');

function getMyWords() {
return $this->getManyManyComponents('Words'); //This works great!
}
....
}

class Word extends DataObject {
....
static $belongs_many= array('Sentences' => 'Sentence');
...
function getMySentances() {
return $this -> getManyManyComponents('Sentences'); // This does not work. What to do? Can it be done?
}
...
}

Avatar
UncleCheese

Forum Moderator, 4092 Posts

16 April 2009 at 3:48pm

Have you tried just:

return $this->Sentences() ?

Avatar
jahbini

Community Member, 13 Posts

17 April 2009 at 2:19am

No, $this -> Sententences() was my very first stab at this, and it was not working, but I did a bit of spelunking into the caverns of Sapphire, and found another (undocumented? underdocumented?) static array called

belongs_many_many

I added that to the class 'Word' and it seems to work (cool!), but are 'belongs_many' and 'belongs_many_many' both required?

class Sentence extends DataObject {
....
static $many_many = array( 'Words' => 'Word');

function getMyWords() {
return $this->getManyManyComponents('Words'); //This works great!
}
....
}

class Word extends DataObject {
....
static $belongs_many= array('Sentences' => 'Sentence');
static $belongs_many_many = array('Sentences' => 'Sentence');
...
function getMySentances() {
return $this -> getManyManyComponents('Sentences'); // This NOW does work.
}
...
}

Avatar
UncleCheese

Forum Moderator, 4092 Posts

17 April 2009 at 2:25am

Weird.. I've never heard of belongs_many. Only belongs_many_many. You definitely want belongs_many_many in your words object. Not sure what belongs_many is...

Avatar
Ingo

Forum Moderator, 801 Posts

26 April 2009 at 10:58pm

Uhm, there is no such thing as "belongs_many" - and I'm fairly certain that $myWord->Sentences() should work out of the box, without you having to overload getMySentances() (please note the spelling mistake from your code). We're using belongs_many_many accessors in our DataObjectTest unit tests, and they don't give us any trouble.

Avatar
jahbini

Community Member, 13 Posts

27 April 2009 at 5:25am

Yes! Thanks for that. I'll just get rid of the belongs_many from my code (and my brain).