小さな Web サイトで Kohana に移行したいと考えており、SQL、PHP、およびビューを分離しようとしていますが、これにはいくつか問題があります。
私はテーブルにいる必要があります。すべてのカテゴリに複数の製品を含めることができます。
カテゴリー表
- ID
- カテゴリー
製品表
- ID
- カテゴリ 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();
ビュー ファイルのコード (説明はコメントを参照):
// 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 />';
}
これが他の人にも役立つことを願っています。誰かがより良い解決策を持っている場合は、共有してください!