Yii 2 связь многие-ко-многим

основная статья

нужно установить дополнение 
(если не понятно - пишите в комментах)

\yii2basic\composer.json

{
    "name": "yiisoft/yii2-app-basic",
    "description": "Yii 2 Basic Project Template",
    "keywords": ["yii2", "framework", "basic", "project template"],
    "homepage": "http://www.yiiframework.com/",
    "type": "project",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/yii2/issues?state=open",
        "forum": "http://www.yiiframework.com/forum/",
        "wiki": "http://www.yiiframework.com/wiki/",
        "irc": "irc://irc.freenode.net/yii",
        "source": "https://github.com/yiisoft/yii2"
    },
    "minimum-stability": "stable",
    "require": {
        "php": ">=5.4.0",
        "yiisoft/yii2": ">=2.0.5",
        "yiisoft/yii2-bootstrap": "*",
        "yiisoft/yii2-swiftmailer": "*",
        "voskobovich/yii2-many-many-behavior": "*"
    },
    "require-dev": {
        "yiisoft/yii2-codeception": "*",
        "yiisoft/yii2-debug": "*",
        "yiisoft/yii2-gii": "*",
        "yiisoft/yii2-faker": "*"
    },
    "config": {
        "process-timeout": 1800
    },
    "scripts": {
        "post-create-project-cmd": [
            "yii\\composer\\Installer::postCreateProject"
        ]
    },
    "extra": {
        "yii\\composer\\Installer::postCreateProject": {
            "setPermission": [
                {
                    "runtime": "0777",
                    "web/assets": "0777",
                    "yii": "0755"
                }
            ],
            "generateCookieValidationKey": [
                "config/web.php"
            ]
        },
        "asset-installer-paths": {
            "npm-asset-library": "vendor/npm",
            "bower-asset-library": "vendor/bower"
        }
    }
}


    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'name' => 'имя',
            'race_id' => 'раса',
            'img' => 'изображение',
            'desc' => 'описание',
        ];
    }


DDL таблиц

unit
CREATE TABLE `unit` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` tinytext NOT NULL COMMENT 'имя',
  `race_id` int(11) NOT NULL COMMENT 'раса',
  `img` tinytext NOT NULL COMMENT 'изображение',
  `desc` tinytext NOT NULL COMMENT 'описание',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `race_id` (`race_id`),
  CONSTRAINT `unit_fk1` FOREIGN KEY (`race_id`) REFERENCES `race` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 PACK_KEYS=0;

perk
CREATE TABLE `perk` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `desc` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_2` (`id`),
  KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

unit_has_perk
CREATE TABLE `unit_has_perk` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `perk_id` int(11) NOT NULL,
  `unit_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `FK_unit_has_perk` (`perk_id`),
  KEY `unit_id` (`unit_id`),
  CONSTRAINT `unit_has_perk_fk1` FOREIGN KEY (`perk_id`) REFERENCES `perk` (`id`),
  CONSTRAINT `unit_has_perk_fk2` FOREIGN KEY (`unit_id`) REFERENCES `unit` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



view \yii2basic\modules\person\views\unit\_form.php

use yii\helpers\ArrayHelper;
use app\modules\person\models\Perk;
<?= $form->field($model, 'perks_list')
      ->dropDownList(ArrayHelper::map(Perk::find()->all(), 'id', 'name'), ['multiple' => true]) ?>
    
model \yii2basic\modules\person\models\Unit.php

    public function rules()
    {
        return [
            [['name', 'race_id', 'desc'], 'required'],
            [['name', 'desc'], 'string'],
            [['race_id'], 'integer'],
            //[['img'], 'file', 'skipOnEmpty' => false],
            [['img'], 'file'],
            [['perks_list'], 'safe'],
        ];
    }

    public function getPerks()
    {
        return $this->hasMany(Perk::className(), ['id' => 'perk_id'])
                        ->viaTable('pers_has_perk', ['pers_id' => 'id']);
    }

    public function behaviors()
    {
        return [
            [
                'class' => \voskobovich\behaviors\ManyToManyBehavior::className(),
                'relations' => [
                    'perks_list' => 'perks',
                ],
            ],
        ];
    }

    public function getMyperks()
    {
        $perks = $this->perks;
        for($i = 0; $i <= count($perks); $i++)
        {
            if (!empty($perks[$i]['name']))
                $perk[] = Html::a($perks[$i]['name'], ['/person/perk/view', 'id' => $perks[$i]['id'],], ['class' => 'btn btn-link']);
        }
        return ($perk) ? implode($perk) : '';
    }

\yii2basic\modules\person\views\unit\index.php

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use app\modules\person\models\Race;
use app\modules\person\models\Unit;
use yii\helpers\Url;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\person\models\UnitSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Units';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="unit-index">

    <h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]);   ?>

    <p>
    <?= Html::a('Create Unit', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?php //echo print_r($model->perks_list); ?>
    <?=
    GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            [
                'class' => 'yii\grid\SerialColumn'
            ],
            //'id',
            [
                'format' => 'raw',
                'label' => 'lol',
                'value' => function($data)
                {
                    return $data->myperks;
                },
            ],
            //implode(",",'perks_list') , 
            //   'img:ntext',
            ['attribute' => 'desc', 'filter' => false],
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]);
    ?>
</div>


F:\OpenServer\domains\yii2basic\modules\person\views\unit\view.php
<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use app\modules\person\models\Race;

/* @var $this yii\web\View */
/* @var $model app\modules\person\models\Unit */

$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Units', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="unit-view">

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

    <p>
        <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
        <?=
        Html::a('Delete', ['delete', 'id' => $model->id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ])
        ?>
    </p>

    <?=
    DetailView::widget([
        'model' => $model,
        'attributes' => [         
            'id',
            'name:ntext',
            ['label' => 'раса', 'value' => $model->race->name,],
            [
                'format' => 'raw',
                'label' => 'lol',
                'value' => $model->myperks,
            ],
            'img:ntext',
            'desc:ntext',
        ],
    ])
    ?>

</div>





Комментарии

Популярные сообщения из этого блога

Пишем логи на C# (.NET). Легкий способ.

Учебник yii2

Автоматический вход пользователя на сервер посредством putty (протокол SSH)