Welcome Guest, Not a member yet? Register   Sign In
Relationship puzzle
#1

[eluser]Unknown[/eluser]
I have 2 tables 'plants' and 'categories' with a many-to-many relationship, and using a linking table 'categories_plants' have populated the linking table successfully using datamapper

however, I am stumped when trying to extract data from the plants table by category ('slug' - in this case hard coded as 'Climbers')as all I can get is the id of the plant but no other fields.
using :

function search($value='Climbers'){

$c = new Category();
$c->where('slug',$value)->get();

$p = $c->plant->get();

foreach ($p as $plant){
echo "$plant->id <br/>";
}
}

..I get a listing of the correct ids for plants in category 'Climbers'.
However, I cannot access any other fields from the Plant data eg. $plant->name etc.
Is it possible? I thought $p would be a collection containing all the data related to the individual plants (from the 'plants' table), but it appears to be only the the data held in the linking table. I would appreciate any input that could shed some light on this.
#2

[eluser]WanWizard[/eluser]
Are you sure you're seeing the plant's id?

$c->plant->get() will return $this, which is $c. So you're seeing the Category's id. If you have issues like this, var_dump() the entire object so know what your looking at.

What does work:
Code:
function search($value=‘Climbers’){

    $c = new Category();
    $c->where(‘slug’,$value)->get();  
  
    $c->plant->get();
  
    foreach ($c->plant as $plant){      
        echo “$plant->id <br>”;
    }  
}

Or even quicker (because it only uses one query):
Code:
function search($value=‘Climbers’){

    $p = new Plant();
    $p->where_related_category(‘slug’,$value)->get();  
  
    foreach ($p as $plant){      
        echo “$plant->id <br>”;
    }  
}
#3

[eluser]Unknown[/eluser]
Thanks for the input.
It turns out I was suffering from a classic programmer's error - tunnel vision, focussing on the datamapper usage only- and hadn't checked the database table (written by somebody else) so, looking for 'name' as a field was plain stupid as the field was called 'common_name' (doh). In fact my original script did work!

However, your second suggestion led me to investigate the 'where_related_{category}' stuff in the documentation, and I realised there was a whole area of datamapper that I hadn't gone into. I had found the raw documentation a bit obtuse , but now with a practical example of my own, it has started to make some sense.




Theme © iAndrew 2016 - Forum software by © MyBB