Handling Many To Many Relation (View)

I’m having a lot of difficult to handle many to many relation (or relation with pivot table) in yii2.

I have the "article", "category" and the "article_has_category" tables.

Model - Article.php




/**

 * @return \yii\db\ActiveRelation

 */

public function getArticleHasCategory()

{

	return $this->hasOne(ArticleHasCategory::className(), ['Article_id' => 'Id']);

}


/**

 * @return \yii\db\ActiveRelation

 */

public function getCategories()

{

	return $this->hasMany(Category::className(), ['Id' => 'Category_id'])->viaTable('article_has_category', ['Article_id' => 'Id']);

}



View - view.php




<?php


use yii\helpers\Html;

use yii\widgets\DetailView;


/**

 * @var yii\web\View $this

 * @var app\models\Article $model

 */


$this->title = $model->Title;

$this->params['breadcrumbs'][] = ['label' => 'Articles', 'url' => ['index']];

$this->params['breadcrumbs'][] = $this->title;

?>

<div class="article-view">


	<h1><?= Html::encode($this->title) ?></h1>


	<p>

		<?= Html::a('Update', ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>

		<?php echo Html::a('Delete', ['delete', 'id' => $model->Id], [

			'class' => 'btn btn-danger',

			'data-confirm' => Yii::t('app', 'Are you sure to delete this item?'),

			'data-method' => 'post',

		]); ?>

	</p>


	<?php echo DetailView::widget([

		'model' => $model,

		'attributes' => [

			'Id',

			'Title',

			'Body:ntext',

		],

	]); ?>

	


</div>



How can I present the categories in the view?

Many thanks in advance

have you tried anything like:




$article = Article::find($id);

foreach ($article->categories as $category) {

   echo $category->id;

}



It gives the error “Class ‘Article’ not found”

However I’ve managed it based upon your code

Many thanks




foreach ($model->categories as $category) {

   echo $category->id;

}



glad you managed it. As a general note when Yii cannot find a class the first thing to check is if the namespace of the class you are using has been properly declared! My code above was just an example how to handle the relation not a defacto code to copy paste :)

You have helped me a lot. Many thanks for that.

Could you please help me in just one more thing?

I have in the Article model




public function getCategoryList() { 

  return ArrayHelper::map(Category::find()->asArray()->all(), 'Id', 'Name');

}



but I have no idea how to present the checkbox to input the categories in the _form.

I’m sure you know how and you will point me to the right direction

checkbox? or a dropdown? Currently Article::getCategoryList() returns an array.

With this array you can build a checkboxlist like below




Html::activeCheckboxList($model, 'attribute', $model->getCategoryList());



or a dropdown :




Html::activeDropDownList($model, 'attribute', $model->getCategoryList());



Hope this helps steer you in the right direction

Yes. I’ve achieved it.

You are helping me a lot but, to be honest my head is totally confused.

You have mentioned getCategoryList() was returning an array. I’ve done it like that because I’ve seen that solution in this forum. But I don’t know if it is the best solution or practice.

Should/can I use arrays or should/can I use objects?

And now I have an huge problem (for me) to solve. Update the article.

How can I present the categories field with some of the categories already selected (the ones selected during the creation)?

I had a look in this yii2 blog sample (https://www.google.pt/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCwQFjAA&url=https%3A%2F%2Fgithub.com%2Fschmunk42%2Fyii2-blog&ei=3bgwU4WxD6Ky0QWtzoHYDA&usg=AFQjCNE13sFV5PgeQDyEvoYGd__06YW2Qg), but the post tags are stored in a text field on post table. Not in a pivot table, which is, IMO a better solution. In summary, I still don’t know how to handle pivot table relations in yii2.

I couldn’t find any post in the web with a simple ‘_form’ code example (it should be, at least in yii2 docs on github).

Many thanks once again.

Pivot table relation

Anyone know how to present the checkboxList or any other widget in the update form, with the tags selected during the create article or post, already selected?

I believe this is something most of the people need.

Many thanks in advance.