id -- parent_id -- name
1 -- 0 -- -- -- -- Автоаксессуары //самостоятельная категория
2 -- 0 -- -- -- -- Автозвук //самостоятельная категория
3 -- 0 -- -- -- -- Автоэлектрика //самостоятельная категория
4 -- 1 -- -- -- -- Автоодеяла //у категории есть родительская Автоаксессуары
... -- ...--...
9 -- 2 -- -- -- -- Автомагнитолы //у категории есть родительская Автозвук
Пока выводятся parent_id категорий, но не name. Нудно в столбце вместо parent_id вывести name
Выскакивает ошибка "Trying to get property of non-object"
Модель Category
Код: Выделить всё
<?php
namespace app\modules\admin\models;
use Yii;
/**
* This is the model class for table "category".
*
* @property string $id
* @property string $parent_id
* @property string $name
* @property string $keywords
* @property string $description
*/
class Category extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'category';
}
public function getCategory(){
return $this->hasOne(Category::className(), ['id' => 'parent_id']);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['parent_id'], 'integer'],
[['name'], 'required'],
[['name', 'keywords', 'description'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => '№ категории',
'parent_id' => 'Родительская категория',
'name' => 'Название',
'keywords' => 'Ключевые слова',
'description' => 'Мета-описание',
];
}
}
Код: Выделить всё
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => Category::find()->with('category'),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
Код: Выделить всё
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Categories';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="category-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create Category', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
// 'parent_id',
[
'attribute' => 'parent_id',
'value' => function($data){
return $data->category->name ? $data->category->name : 'Самостоятельная категория';
},
],
'name',
'keywords',
'description',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>