0

我有一个“步骤”表,其中包含“id”和名为“step”的步骤文本。然后我有一个带有“id”和其他客户信息的“客户”表。最后,我有一个带有“customer_id”和“step_id”的“customers_steps”连接表。目标是列出步骤,并显示已完成的步骤。但我被困住了...

为了确保我没有遗漏任何东西,在“客户”模型中,我有

var $has_many = array ('step');

在“步骤”模型中,我有

var $has_many = array('customer');

现在,我正在循环这些步骤,然后循环遍历客户的步骤以查看它们是否匹配......但它有很多代码,我知道必须有一个更快的方法,我只是想念它:

$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;
   }
}

这行得通......但我能做些什么来让它变得更好?提前致谢。

4

2 回答 2

1

你有一个多对多的关系,所以你永远无法一次完成。

理想情况下,您需要在步骤和客户步骤之间进行 LEFT JOIN,这将生成一个包含所有步骤的结果集,并且对于特定客户 ID 不存在的那些步骤的 NULL 值。但由于 Datamapper 是关于关系的,它不能报告不存在的关系。

你可以使用

// get the customer and his steps
$c = new Customer(1);
$c->step->get();

// create the list of assigned step id's
$list = array();
foreach ($c->step as $step)
{
    $list[] = $step->id;
}

// get the steps not assigned
$s = new Step();
$s->where_not_in('id', $list);

// at this point $c->steps contains all matching steps
// and $s all steps that don't match
print_r($c->steps->all_to_array());
print_r($s->all_to_array());
于 2010-12-21T23:03:14.447 回答
0

在另一种情况下,我发现很多关系并不那么简单。也许,我要求的魔法太多了。

例如

客户有_many 联系人有_many 地址。

Contacts_Customers 和 Addresses_Contacts 表有一个列 primary = 0 或 1。

我无法获得包含主要联系人和主要地址的所有客户的完整表格。

我可以通过主要联系人获得他们。当我使用第二个“where_join_field”时不起作用。也许我错过了一些东西......

我想了

$c = new Customer();
$c->include_related('contact');
$c->where_join_field('contact','primary','1');
$c->include_related('contact/address');
$c->where_join_field('contact/address','primary','1');
$c->get();

没用。

$c = new Customer();
$c->include_related('contact');
$c->where_join_field('contact','primary','1');
$c->contact->include_related('address');
$c->contact->where_join_field('address','primary','1');
$c->get();

此外,没有工作。

我最终在模型中使用了一个函数来过滤掉主要的 0。本来希望上述之一工作。至于实际的 SQL 命令,我想要的只是另一个 WHEREaddresses_contacts.primary = 1。

于 2011-09-22T16:14:27.613 回答