Kohana에서 카테고리 및 제품을 나열 할 때 SQL, PHP 및보기 분리
-
19-09-2019 - |
문제
나는 작은 웹 사이트를 통해 Kohana로 마이그레이션하고 싶고 SQL, PHP 및 View를 분리하려고하지만 이것에 문제가 있습니다.
테이블이 있어야합니다. 모든 카테고리에는 여러 제품이있을 수 있습니다.
카테고리 테이블
- 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 모듈을 사용하지 않고 솔루션을 선호합니다. BTW 나는 Kohana 3.0을 사용하고 있습니다
Update 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 />';
}
나는 이것이 다른 사람들에게도 도움이 되었기를 바랍니다. 누군가 더 나은 해결책을 가지고 있다면 공유하십시오!
해결책
이것은 작동해야합니다 :
$categories = ORM::factory('category')->find_all();
foreach ($categories as $category)
{
echo '<b>'.$category->category.'</b><br />';
$products = ORM::factory('product')->where('category_id',$category->id)->find();
foreach($products as $product)
{
echo $product->product.'<br />';
}
echo '<hr />';
}
각 테이블에 대한 모델을 만들었다고 생각하십니까? 그렇지 않다면 읽으십시오 여기.
더 나은 데이터를 분리하고 계층을 뷰를 보는 경우. 모델 파일에서 카테고리와 제품 간의 관계를 만듭니다. 그런 다음 컨트롤러에서는 다음과 같이 호출해야합니다.
$categories = ORM::factory('category')->find_all();
$view = new View('yourView');
$viem->categories = $categories;
그리고 파일에서 :
foreach ($categories as $category)
{
echo '<b>'.$category->category.'</b><br />';
foreach($category->products as $product)
{
echo $product->product.'<br />';
}
echo '<hr />';
}
모든 행에 대해 2 차 쿼리를 호출 할 필요는 없습니다. Kohana Orm이 당신을 위해 그것을 할 것입니다. 적절한 모델을 만드는 것입니다.
class Category_Model extends ORM {
protected $has_many = array('products');
}
class Product_Model extends ORM {
protected $belongs_to = array('category');
}
또 다른 접근법 : 테이블 카테고리 및 제품에 가입 할 수 있습니다
$products = DB::select('categories.category AS cat','products.product AS prod')
->from('categories')
->join('products','products.category_id','category.id')
->as_object()
->execute();
그리고:
$current_cat = '';
foreach($products as $product)
{
if($current_cat != $products->cat)
{
echo '<b>'.$products->cat.'</b><br />';
$current_cat = $products->cat;
}
echo $product->prod.'<br />';
}
다른 팁
빠른 생각 :
ORM 접근 방식을 사용할 때는 with () 메소드를 사용하여 조인 쿼리와 동일한 것을 달성 할 수 있다고 생각합니다.
$products = ORM::factory('product')
->with('category')
->find_all();
$view = new View('yourView');
$viem->products = $products;
나는 그것에 대해 엉망으로 할 시간이 충분하지 않았지만 이것이 내가 시도 할 것입니다.