Snippets - Little bits of code to make you happy
Getting items from a has_many or many_many relation
Tweet7 October 2010 | | | Supports v2.4, v2.3
Have you ever found yourself using DataObject::get() to fetch objects in a has_many so that you can filter/sort them easily?
Well as it happens there is no need to do this thanks to a totally undocumented bit of code!
Lets say you have this relationship on your Page:
static $has_many = array( 'MyItems' => 'DataObject' );
you can do this (from with the context of your Page object):
$this->MyItems("FieldA = 'B'", "Field DESC", NUll, 2);
instead of using something like
DataObject::get("MyItems", "PageID = " . $this->ID . " AND FieldA = 'B'", "FieldB DESC", NUll, 2);
Much better!
This can be especially useful when you have interrelating relationships, it will save you having to use a manual join.
Special thanks to Daniel Hensby for finding this code and passing it on!
Special Thanks
Special thanks go to Daniel Hensby for their contributions to this post.
5 Comments
RSS feed for comments on this page RSS feed for all comments
Daniel Hensby
07/10/2010 1:09pm (2 years ago)
What a great little bit of code! How did you stumble across this?
Aram Balakjian
07/10/2010 1:49pm (2 years ago)
lol sorry Dan, credit added! :)
Liam Houlahan
21/12/2010 9:07am (1 year ago)
I have come across what I assume is a rare case where I have a self many to many relationship on a dataobject. So the dataobject has got two relationships a many_many and a belongs_many_many with its self.
If I name both of the relationships the same then only the many_many seems to work (when calling it)... If I name them differently then I can only access one at a time.
I have tried to create a function that merges them but that isn't working so far, but I thought I would post here to see if you guys know what the best way would be to retrieve both sides of the relationship with this type of relationship?
Thanks
Liam
Liam Houlahan
21/12/2010 9:10am (1 year ago)
I got the merge function to work. But still is there a better way... Something that is built in to sapphire maybe?
alexyoungs
05/12/2011 11:51am (5 months ago)
Great bit of code!
I'm actually trying to use this in some conditional logic to check if a relationship exists, but it doesn't seem to be working in the way I'd hoped. Here's what I'm trying:
$groups = DataObject::get("Group");
if($follower = $groups->Followers("FollowerID = '2'")){ // work with Follower ID 2 }
Groups have a many_many relationship with Followers, so I was expecting a DataObject or a false return, but I'm not getting a false if the relationship doesn't exist.
I can go about things in a different (albeit more long winded way), but to put my mind at rest, is what I'm trying to do possible?
Post a comment ...
You cannot post comments until you have logged in. Login Here.