2016-03-25 3 views
0

私は2テーブルに参加しましたが、今度はフィールド<th>Categories name</th>にカテゴリの名前を表示したいと思います。 <?php foreach ($posts as $post){ ?>でどうすればいいですか? <?=$post->categories.name?>のようにレンダリングしますか?私はここで立ち往生している。Yii2参加後のデータを表示

ありがとうございます。

マイコントローラ:

public function actionIndex() 
{ 

    $query = posts::find()->leftJoin('categories', 'posts.cate_id = categories.id'); 
    $cates = Categories::find()->all(); 
    $posts= $query->orderBy(['create_date' => SORT_DESC])->all(); 
    $images = Images::find()->all(); 
    $searchModel = new PostsSearch(); 
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

    return $this->render('index', [ 
     'posts' => $posts, 
     'dataProvider' => $dataProvider, 
      'searchModel' => $searchModel, 
      'cates' => $cates, 
      'images' => $images, 
    ]); 
} 

マイビュー:

<thead> 
<tr> 
    <th>ID</th> 
    <th>Name</th> 
    <th>Create Date</th> 
</thead> 
<tbody> 
<?php foreach ($posts as $post){ ?> 
<tr> 
    <td><?= $post->id ?></td> 

    <th><?= Html::a($post->name, ['post/view', 'id'=>$post->id]) ?></th> 

    <td><?= $post->create_date ?></td> 

    </tr> 
    <?php } ?> 
    </tbody> 

答えて

0

ループだけの記事と同じようにカテゴリを。それは同じ原理です。

foreach($posts as $post) 
    foreach($post->categories as $category) 
     echo $category->name; 

これは、モデルで適切な関係を定義していることを前提としています。

I.e.外部キーを介して:

public function getCategories() 
{ 
    return $this->hasMany(Category::className(), ['post_id' => 'id']); 
} 

あなたはそれを逆にしているようです。ポストではcategory_idを持つことができますが、そのカテゴリは1つのカテゴリに限定されます。区切り文字で区切られたフィールドにIDを格納しない限り、しかし、そのオプションはもう少し作業が必要です。

関連する問題