Welcome Guest, Not a member yet? Register   Sign In
Datamapper - return distinct objects from one to many join
#1

I'm trying to get my head around whether datamapper is the right ORM for me.

I've set up classes Product and Productimage, with a one to many relationship (a product can have many images). When I retrieve a list of products and related images, any product with multiple images is represented multiple times in the result set. Is there any way around this?
PHP Code:
class Product extends DataMapper {
 
   public $has_many = array('productimage');
}

class 
Productimage extends DataMapper {
 
   public $has_one = array('product');
}

$products = new Product();
$products->include_related("productimage",nulltruetrue);
$products->get();
foreach(
$products as $product){

    echo 
"\nProduct : ".$product->name."\n";
    echo 
"Images:\n";
    foreach(
$product->productimage as $image){
        echo 
"\t".$image->filename."\n";
    }

This outputs:
Code:
Product : Hammer
Images:
    hammerpic1.jpg

Product : Hammer
Images:
    hammerpic2.jpg

Product : Screwdriver
Images:
    screwdriver1.jpg

Product : Saw
Images:
    saw1.jpg

Product : Saw
Images:
    saw2.jpg

The database query returns:
Code:
   id  name         productimage_id  productimage_filename  productimage_product_id  
------  -----------  ---------------  ---------------------  -------------------------
    1  Hammer                     1  hammerpic1.jpg                                 1
    1  Hammer                     2  hammerpic2.jpg                                 1
    2  Screwdriver                3  screwdriver1.jpg                               2
    3  Saw                        4  saw1.jpg                                       3
    3  Saw                        5  saw2.jpg                                       3

I understand why a join can cause the result set to have many entries for each product, but is it not possible for datamapper to identify that it already has that product's id, and add subsequent rows to that products's productimages collection?

I considered using distinct, but the rows are already distinct (as they've got different images on each row).
I considered using group by, but that simply removed subsequent result for each product.

Any other options I'm not aware of?
Reply
#2

This is simply the way one-to-many and many-to-many relationships work in SQL. You may have better luck finding specific options for Datamapper in a forum specific to it, but, lacking any option to change its behavior, your best bet would be to loop through the result set in your model or controller and create a new dataset based on the output you desire.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB