Welcome Guest, Not a member yet? Register   Sign In
Datamapper include_related group values to one object
#1

[eluser]Sport_Billy[/eluser]
I am having 3 tables

Code:
customers
   id  
   firstname
   lastname
deseases
   id
   desease_name
customers_deseases
   id
   customer_id
   desease_id

And i want to get the deseases of each customer.
For example let's say that customer John Smith has desease1 and desease2.
When using this code:

Code:
$customer = new Customer();
$customer->include_related('desease', array('desease_name'), true, true);
$customers = $customer->get();

And trying to see the results like this:

Code:
foreach($customers as $c){
                echo $c->firstname . $c->lastname;
                echo "<br/>";
                foreach($c->desease as $cd)
                {
                    echo $cd->desease_name;  
                    echo "<br/>";
                }
        }

The returning object has the customer in 2 separate objects like this
Code:
John Smith desease1
John Smith desease2

While i want something like this:
Code:
John Smith
desease1
desease2
#2

[eluser]WanWizard[/eluser]
Datamapper doesn't have object instantiation for many-many relations.
#3

[eluser]Sport_Billy[/eluser]
Thanks for your reply WanWizard, it is nice to see you helping here.

I figured it out too that it cannot be supported the way i did it with include_related.
I ended up using subqueries and GROUP_CONCAT function, because it still does what i wanted.

Here is the code i used based on the example above in case someone has similar problem:

Code:
$customer = new Customer();
        $deseases = $customer->desease;
        $deseases->select_func('GROUP_CONCAT', '@desease_name', 'group_concat');
        $deseases->where_related('customer', 'id', '${parent}.id');
        $customer->select_subquery($deseases, 'desease_names');
        $customer->get();

So the results for the example will come from this output:

Code:
foreach($customers as $c){
                echo $c->firstname . $c->lastname;
                echo "<br/>";
                echo $c->desease_names;
                echo "<br/>";
        }


And will produce something like this:

Code:
John Smith
desease1, desease2




Theme © iAndrew 2016 - Forum software by © MyBB