【发布时间】:2009-09-30 15:29:17
【问题描述】:
我想用我的小网站迁移到 Kohana,我正在尝试将 SQL、PHP 和视图分开,但是我遇到了一些问题。
我必须要桌子。每个类别可以有多个产品。
类别表
- 身份证
- 类别
产品表
- 身份证
- category_id
- 产品
这是我之前的代码(转换为 Kohana 的查询生成器):
$categories = DB::select('id', 'category')
->from('categories')
->as_object()
->execute();
foreach ($categories as $category)
{
echo '<b>'.$category->category.'</b><br />';
$products = DB::select('product')
->from('products')
->where('category_id', '=', $category->id)
->as_object()
->execute();
foreach($products as $product)
{
echo $product->product.'<br />';
}
echo '<hr />';
}
我也想做同样的事情,只是在我不想使用的视图文件中,除了回显变量。
更新: 我更喜欢不使用 Kohana 的 ORM 模块的解决方案。 顺便说一句,我正在使用 Kohana 3.0
更新 2:
我已接受 Lukasz 的最后一个解决方案,但需要进行一些修改才能完全按照我的意愿进行(注意这是针对 Kohana 3.0,而 Lukasz 使用的是旧版本):
SQL 代码:
$products = DB::select(array('categories.category', 'cat'), array('products.product', 'prod'))
->from('categories')
->join('products','RIGHT')
->on('products.category_id','category.id')
->as_object()
->execute();
视图文件中的代码(解释见cmets):
// Let's define a new variable which will hold the current category in the foreach loop
$current_cat = '';
//We loop through the SQL results
foreach ($products as $product)
{
// We're displaying the category names only if the $current_cat differs from the category that is currently retrieved from the SQL results - this is needed for avoiding the category to be displayed multiple times
// At the begining of the loop the $current_cat is empty, so it will display the first category name
if($curren_cat !== $product->cat)
{
// We are displaying a separator between the categories and we need to do it here, because if we display it at the end of the loop it will separate multiple products in a category
// We avoid displaying the separator at the top of the first category by an if statement
if($current_cat !== '')
{
//Separator
echo '<hr />';
}
// We echo out the category
echo '<b>'.$product->cat.'</b><br />';
// This is the point where set the $current_cat variable to the category that is currently being displayed, so if there's more than 1 product in the category the category name won't be displayed again
$current_cat = $product->cat;
}
// We echo out the products
echo $product->prod.'<br />';
}
我希望这也对其他人有所帮助,如果有人有更好的解决方案,请分享!
【问题讨论】:
标签: php mysql kohana kohana-orm