I’ve got a “steps” table, with the “id” and the text of the step named “step”. Then I have a “customers” table with “id” and other customer info. Finally, I have a “customers_steps” join table with “customer_id” and “step_id”. The goal is to have a list of steps, and show which ones were completed. But I’m stuck…
To make sure I’m not missing anything, in the “customer” model, I have
var $has_many = array ('step');
In the “step” model, I have
var $has_many = array('customer');
Right now, I’m looping the steps, then looping through the customer’s steps to see if they match… but it’s a lot of code, and I KNOW there has to be a faster way, and I’m just missing it:
$c = new Customer();
$c->get_by_id(1);
$c->step->get();
$s = new Step();
$s->get();
foreach($s as $step)
{
foreach($c as $customer)
{
if($customer->step->id == $step->id)
{
$match = true;
}
}
if($match)
{
echo "match - " . $step->step;
}
else
{
echo $step->step;
}
}
This works… but what can I do to make it better? Thanks in advance.
You have a many-to-many relationship, so you’ll never be able to do this in one go.
Ideally, you need a LEFT JOIN between steps and customers_steps, which would produce a resultset with all steps in it, and a NULL value for those steps not present for a specific customer id. But since Datamapper is about relationships, it can’t report relations that aren’t there.
You could use