Skip to content

Commit

Permalink
0.1.0 release
Browse files Browse the repository at this point in the history
  • Loading branch information
arogachev committed Apr 12, 2015
0 parents commit c652b4e
Show file tree
Hide file tree
Showing 7 changed files with 645 additions and 0 deletions.
30 changes: 30 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Yii 2 Many-to-many extension for Yii 2 framework is free software.
It is released under the terms of the following BSD License.

Copyright © 2015, Alexey Rogachev (https://github.com/arogachev)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of test nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
186 changes: 186 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
# Yii 2 Many-to-many

Implementation of [Many-to-many relationship](http://en.wikipedia.org/wiki/Many-to-many_%28data_model%29)
for Yii 2 framework.

- [Installation](#installation)
- [Features](#features)
- [Creating editable attribute](#creating-editable-attribute)
- [Attaching and configuring behavior](#attaching-and-configuring-behavior)
- [Adding attribute as safe](#adding-attribute-as-safe)
- [Adding control to view](#adding-control-to-view)

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist arogachev/yii2-many-to-many
```

or add

```
"arogachev/yii2-many-to-many": "*"
```

to the require section of your `composer.json` file.

## Features

- Configuring using existing ```hasMany``` relations
- Multiple relations
- No extra queries. For example, if initially model has 100 related records,
after adding just one, exactly one row will be inserted. If nothing was changed, no queries will be executed.
- Auto filling of editable attribute for given route(s)
- Validator for checking if the received list is valid

## Creating editable attribute

Simply add public property to your `ActiveRecord` model like this:

```php
/**
* @var array
*/
public $users = [];
```

It will store primary keys of related records during update.

## Attaching and configuring behavior

First way is to explicitly specify all parameters:

```php
use arogachev\ManyToMany\behaviors\ManyToManyBehavior;

/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ManyToManyBehavior::className(),
'relations' => [
[
'editableAttribute' => 'users', // Editable attribute name
'table' => 'tests_to_users', // Name of the junction table
'ownAttribute' => 'test_id', // Name of the column in junction table that represents current model
'relatedModel' => User::className(), // Related model class
'relatedAttribute' => 'user_id' // Name of the column in junction table that represents related model
'fillingRoute' => 'tests/default/update', // Full route name (including module id if it's inside module) for auto filling editable attribute with existing data. You can also pass array of routes.
],
],
],
];
}
```

But more often we also need to display related models,
so it's better to define relation for that and use it for both display and behavior configuration.
Both ways (```via``` and ```viaTable```) are considered valid:

Using ```viaTable```:

```php
/**
* @return \yii\db\ActiveQuery
*/
public function getRelUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('tests_to_users', ['test_id' => 'id'])
->orderBy('name');
}
```

Using ```via``` (requires additional model for junction table):

```php
/**
* @return \yii\db\ActiveQuery
*/
public function getRelTestUsers()
{
return $this->hasMany(TestUser::className(), ['test_id' => 'id']);
}

/**
* @return \yii\db\ActiveQuery
*/
public function getRelUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->via('relTestUsers')
->orderBy('name');
}
```

Order is not required.

Then just pass the name of this relation and all other parameters will be fetched automatically.

```php
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => ManyToManyBehavior::className(),
'relations' => [
[
'name' => 'relUsers',
// These are the same as in previous example
'editableAttribute' => 'users',
'fillingRoute' => 'tests/default/update',
],
],
],
];
}
```

Additional many-to-many relations can be added exactly the same.
Note that even for one relation you should declare it as a part of `relations` section.

## Adding attribute as safe

Add editable attribute to model rules for massive assignment.

Either mark it as safe at least:

```php
public function rules()
{
['users', 'safe'],
}
```

Or use custom validator:

```php

use arogachev\ManyToMany\validators\ManyToManyValidator;

public function rules()
{
['users', ManyToManyValidator::className()],
}
```

Validator checks list for being array and containing only primary keys presented in related model.
It can not be used without attaching `ManyToManyBehavior`.

## Adding control to view

Add control to view for managing related list. Without extensions it can be done with multiple select:

```php
<?= $form->field($model, 'users')->dropDownList(User::getList(), ['multiple' => true]) ?>
```
72 changes: 72 additions & 0 deletions behaviors/ManyToManyBehavior.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

namespace arogachev\ManyToMany\behaviors;

use arogachev\ManyToMany\components\ManyToManyRelation;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;

class ManyToManyBehavior extends Behavior
{
/**
* @var array
*/
public $relations = [];

/**
* @var ManyToManyRelation[]
*/
protected $_relations = [];


/**
* @inheritdoc
*/
public function events()
{
return [
ActiveRecord::EVENT_INIT => 'customInit',
ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
];
}

public function customInit()
{
foreach ($this->relations as $config) {
$config['model'] = $this->owner;
$this->_relations[] = new ManyToManyRelation($config);
}
}

public function afterFind()
{
foreach ($this->_relations as $relation) {
$relation->fill();
}
}

public function afterInsert()
{
foreach ($this->_relations as $relation) {
$relation->insert();
}
}

public function afterUpdate()
{
foreach ($this->_relations as $relation) {
$relation->update();
}
}

/**
* @return ManyToManyRelation[]
*/
public function getManyToManyRelations()
{
return $this->_relations;
}
}
Loading

0 comments on commit c652b4e

Please sign in to comment.