我是CodeIgniter的新手。
我为Pizza table和Ingredients表创建了模型。表格由额外的Pizza_Ingredients表连接(其多对多关系)。
我的模特:
<?php
class Pizza extends DataMapper {
var $table = 'Pizza';
var $has_many =
array(
'ingredients' =>
array(
'class' => 'ingredients',
'join_table' => 'pizza_ingredients'
)
);
}
class Ingredients extends DataMapper {
var $table = 'Ingredients';
var $has_many =
array(
'pizza' =>
array(
'class' => 'pizza',
'join_table' => 'pizza_ingredients'
)
);
}
?>
当我使用该代码获取数据时:
$pm = new Pizza();
$pm->include_related('ingredients');
$array = $pm->get();
我正在获取具有重复的Pizza值的数组(它看起来只是sql查询结果)。
margherita | cheese
vegetariana | vegetable 1
vegetariana | vegetable 2
我不能简单地在数组上的“foreach”中生成html表格。
我想得到具有这样结构的对象:
margherita:
- cheese
vegetariana:
- vegetable 1
- vegetable 2
允许我在“披萨圈”中使用其他foreach循环(含有成分)制作foreach循环(使用比萨饼)。
我必须用PHP编写,或者CodeIgniter / DataMapper可以为我做更多的事情吗?
有什么建议吗?
答案 0 :(得分:1)
我只是坚持同样的答案......
所以,搜索CI Datamapper DOC,我找到了一些有用的东西(http://datamapper.wanwizard.eu/pages/getadvanced.html),看看第一个例子!
翻译成您的问题,应该是这样的:
// Create pizza
$pm = new Pizza();
// DO NOT USE include_related to Ingredients Here !!!
//Datamapper will DO THIS for you!
// Remember to declare your Ingredients class in singular, not plural
// So your class should be in singular -> Ingredient
// And your DB Table should be in plural -> Ingredients
// As CI Datamapper Guide teaches :)
// Get all pizzas
$pm->get();
// Loop through all pizzas
foreach ($pm as $pizza)
{
// Print the actual pizza name
echo $pizza->name."<br/>";
// Get the current pizza's Ingredients <- Here is the magic comes!
$pizza->ingredient->get();
// Print all current pizza's Ingredients
foreach ($pizza->ingredient as $ingredient)
{
echo $ingredient->name."<br/>";
}
}
这项工作对我来说非常好,但它会持续很多次,实际上,数据库包含的每个披萨都会有一次。
如果使用CI Datamapper的某些解决方案对DB的请求较少,我真的很感激。
如果找到,请分享!
答案 1 :(得分:0)
为什么不使用中间表来分解多对多的关系。似乎更容易管理。像:
TABLE pizza_ingredients
id
pizza_id
ingredient_id
然后你可以尝试这样的事情:
foreach($pizzas as $pizza)
$pizza->ingredients = $this->get_ingredients($pizza->id);
答案 2 :(得分:-1)
您可以设置一个变量,它是您当前所在的披萨,并在下一次迭代时检查它。你的格式和诸如此类的东西会有所不同,但这会给你一个想法。
foreach ($pizza as $k=>$p) {
if ($last_pizza === $p->pizza) {
echo "<tr>
<td>
</td>
</tr>
<tr>
<td>
$p->cheese
</td>
</tr>";
$last_pizza = $p->pizza;
}else{
echo "<tr>
<td>
$p->pizza
</td>
</tr>
<tr>
<td>
$p->cheese
</td>
</tr>";
$last_pizza = $p->pizza;
}
}