문제

I have a table "categories". Each category could have a parent category.

 Categories
    id 
    parent_category
    title

There is only one parent_category for each category

My questions are :

  1. What is the code for the Category model?
  2. Given a category '$category' what do I type to output the parent category title?
도움이 되었습니까?

해결책

You might try the following...

<?php

class Category extends ActiveRecord\Model {
   static $belongs_to = array(
        array('parent', 'foreign_key' => 'parent_category', 'class_name' => 'Category')
   );

   static $has_many = array(
        array('children', 'foreign_key' => 'parent_category', 'class_name' => 'Category'),
    );

}

You can simply retrieve the parent category:

$category = Category::find(1); 
print 'Parent Title : ' . $category->parent->title;

Or retrive all children categories:

$categoryParent = Category::find(1);
// loop through all child elements...
foreach ($categoryParent->children as $category)  {
    print $category->title . ' <br/>';
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top