Welcome Guest, Not a member yet? Register   Sign In
DataMapper ORM - How to get all of a model and each instance's related data
#1

[eluser]coderego[/eluser]
I do not understand how to do the following:

Lets say I have a product table, and a photo table. 1 Product has many photos. So in the product model I do:

Code:
var $has_many = array("category", "photo");
Now I want to get all products and relate each of their photos to them. How can I do this? Currently, in my controller I am going through each of the products and querying photos and passing a separate array that way. This CANNOT be ideal. I should be able to tie each photo to the specific product directly no?

Logically, this would work (but it doesnt?)

Code:
$product = new Product;
$products = $product->get_by_related_category('name', $where);
$photos = $product->photo->get();
See what I'm getting at? I would love to just pass that $products variable to my view, be able to foreach through it, and have an array of photos tied to each product object.

How can I accomplish this? Or is there a better way to do this?

Thanks!
#2

[eluser]WanWizard[/eluser]
There is no option at the moment to get all products with all related has_many objects, in one go. You can do it with has_one's, using include_related() and the $instantiate flag.

This hasn't been implemented for has_many in DM because is has a design which is over 5 years old, from the time that CI was PHP4, and instantiating many objects was (and still is to an extend) very expensive. If you have 500 products, with on average 10 photo's, you'll have to hydrate 5000 objects. That is never going to be fast.
#3

[eluser]coderego[/eluser]
Understood

So what's a good way to accomplish the task of getting the photo for each picture?


I should also state that I am really only interested in
1) getting one photo for each product
2) getting all photos for one product

My photo table is defined as:

id
product_id
splash

For the first case I'd want the photo where splash =1 for a given product id


Thanks!

#4

[eluser]WanWizard[/eluser]
For the first one it would be something like:

Code:
$product = new Product;
$product->include_related('photo')->where_related_photo('splash', 1)->get();

and for getting all photo's for a product:

Code:
$photo = new Photo;
$photo->where('product_id', $productid)->get();




Theme © iAndrew 2016 - Forum software by © MyBB