{"id":15169493,"url":"https://github.com/yii2tech/ar-linkmany","last_synced_at":"2025-10-01T02:31:20.170Z","repository":{"id":57087028,"uuid":"41366766","full_name":"yii2tech/ar-linkmany","owner":"yii2tech","description":"ActiveRecord behavior for saving many-to-many relations","archived":true,"fork":false,"pushed_at":"2019-07-03T11:35:45.000Z","size":23,"stargazers_count":86,"open_issues_count":0,"forks_count":17,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-09-22T22:01:56.787Z","etag":null,"topics":["activerecord","many2many","yii","yii2","yii2-extension"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yii2tech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["klimov-paul"],"patreon":"klimov_paul"}},"created_at":"2015-08-25T14:04:52.000Z","updated_at":"2024-08-02T02:19:58.000Z","dependencies_parsed_at":"2022-08-25T00:50:50.284Z","dependency_job_id":null,"html_url":"https://github.com/yii2tech/ar-linkmany","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-linkmany","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-linkmany/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-linkmany/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-linkmany/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yii2tech","download_url":"https://codeload.github.com/yii2tech/ar-linkmany/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219875269,"owners_count":16554660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","many2many","yii","yii2","yii2-extension"],"created_at":"2024-09-27T07:02:17.129Z","updated_at":"2025-10-01T02:31:14.873Z","avatar_url":"https://github.com/yii2tech.png","language":"PHP","funding_links":["https://github.com/sponsors/klimov-paul","https://patreon.com/klimov_paul"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yii2tech\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://avatars2.githubusercontent.com/u/12951949\" height=\"100px\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eActiveRecord Many-to-Many Saving Extension for Yii2\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\nThis extension provides support for ActiveRecord many-to-many relation saving.\nFor example: single \"item\" may belong to several \"groups\", each group may be linked with several items.\nUnlike regular [[\\yii\\db\\BaseActiveRecord::link()]] usage, this extension automatically checks references existence,\nremoves excluded references and provide support for web form composition.\n\nFor license information check the [LICENSE](LICENSE.md)-file.\n\n[![Latest Stable Version](https://poser.pugx.org/yii2tech/ar-linkmany/v/stable.png)](https://packagist.org/packages/yii2tech/ar-linkmany)\n[![Total Downloads](https://poser.pugx.org/yii2tech/ar-linkmany/downloads.png)](https://packagist.org/packages/yii2tech/ar-linkmany)\n[![Build Status](https://travis-ci.org/yii2tech/ar-linkmany.svg?branch=master)](https://travis-ci.org/yii2tech/ar-linkmany)\n\n\nInstallation\n------------\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist yii2tech/ar-linkmany\n```\n\nor add\n\n```json\n\"yii2tech/ar-linkmany\": \"*\"\n```\n\nto the require section of your composer.json.\n\n\nUsage\n-----\n\nThis extension provides support for ActiveRecord many-to-many relation saving.\nThis support is granted via [[\\yii2tech\\ar\\linkmany\\LinkManyBehavior]] ActiveRecord behavior. You'll need to attach\nit to your ActiveRecord class and point the target \"has-many\" relation for it:\n\n```php\nclass Item extends ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'linkGroupBehavior' =\u003e [\n                'class' =\u003e LinkManyBehavior::className(),\n                'relation' =\u003e 'groups', // relation, which will be handled\n                'relationReferenceAttribute' =\u003e 'groupIds', // virtual attribute, which is used for related records specification\n            ],\n        ];\n    }\n\n    public static function tableName()\n    {\n        return 'Item';\n    }\n\n    public function getGroups()\n    {\n        return $this-\u003ehasMany(Group::className(), ['id' =\u003e 'groupId'])-\u003eviaTable('ItemGroup', ['itemId' =\u003e 'id']);\n    }\n}\n```\n\nBeing attached [[\\yii2tech\\ar\\linkmany\\LinkManyBehavior]] adds a virtual proprty to the owner ActiveRecord, which\nname is determined by [[\\yii2tech\\ar\\linkmany\\LinkManyBehavior::$relationReferenceAttribute]]. You will be able to\nspecify related models primary keys via this attribute:\n\n```php\n// Pick up related model primary keys:\n$groupIds = Group::find()\n    -\u003eselect('id')\n    -\u003ewhere(['isActive' =\u003e true])\n    -\u003ecolumn();\n\n$item = new Item();\n$item-\u003egroupIds = $groupIds; // setup related models references\n$item-\u003esave(); // after main model is saved referred related models are linked\n```\n\nThe above example is equal to the following code:\n\n```php\n$groups = Group::find()\n    -\u003ewhere(['isActive' =\u003e true])\n    -\u003eall();\n\n$item = new Item();\n$item-\u003esave();\n\nforeach ($groups as $group) {\n    $item-\u003elink('groups', $group);\n}\n```\n\n\u003e Attention: do NOT declare `relationReferenceAttribute` attribute in the owner ActiveRecord class. Make sure it does\n  not conflict with any existing owner field or virtual property.\n\nVirtual property declared via `relationReferenceAttribute` serves not only for saving. It also contains existing references\nfor the relation:\n\n```php\n$item = Item::findOne(15);\nvar_dump($item-\u003egroupIds); // outputs something like: array(2, 5, 11)\n```\n\nYou may as well edit the references list for existing record, while saving linked records will be synchronized:\n\n```php\n$item = Item::findOne(15);\n$item-\u003egroupIds = array_merge($item-\u003egroupIds, [17, 21]);\n$item-\u003esave(); // groups \"17\" and \"21\" will be added\n\n$item-\u003egroupIds = [5];\n$item-\u003esave(); // all groups except \"5\" will be removed\n```\n\n\u003e Note: if attribute declared by `relationReferenceAttribute` is never invoked for reading or writing,\n  it will not be processed on owner saving. Thus it will not affect pure owner saving.\n\n\n## Creating relation setup web interface \u003cspan id=\"creating-relation-setup-web-interface\"\u003e\u003c/span\u003e\n\nThe main purpose of [[\\yii2tech\\ar\\linkmany\\LinkManyBehavior::$relationReferenceAttribute]] is support for creating\nmany-to-many setup web interface. All you need to do is declare a validation rule for this virtual property in\nyour ActiveRecord, so its value can be collected from the request:\n\n```php\nclass Item extends ActiveRecord\n{\n    public function rules()\n    {\n        return [\n            ['groupIds', 'safe'] // ensure 'groupIds' value can be collected on `populate()`\n            // ...\n        ];\n    }\n\n    // ...\n}\n```\n\nInside the view file you should use `relationReferenceAttribute` property as an attribute name for the form input:\n\n```php\n\u003c?php\nuse yii\\helpers\\ArrayHelper;\nuse yii\\helpers\\Html;\nuse yii\\widgets\\ActiveForm;\n\n/* @var $model Item */\n?\u003e\n\u003c?php $form = ActiveForm::begin(); ?\u003e\n\n\u003c?= $form-\u003efield($model, 'name'); ?\u003e\n\u003c?= $form-\u003efield($model, 'price'); ?\u003e\n\n\u003c?= $form-\u003efield($model, 'groupIds')-\u003echeckboxList(ArrayHelper::map(Group::find()-\u003eall(), 'id', 'name')); ?\u003e\n\n\u003cdiv class=\"form-group\"\u003e\n    \u003c?= Html::submitButton('Save', ['class' =\u003e 'btn btn-primary']) ?\u003e\n\u003c/div\u003e\n\n\u003c?php ActiveForm::end(); ?\u003e\n```\n\nInside the controller you don't need any special code:\n\n```php\nuse yii\\web\\Controller;\n\nclass ItemController extends Controller\n{\n    public function actionCreate()\n    {\n        $model = new Item();\n\n        if ($model-\u003eload(Yii::$app-\u003erequest-\u003epost()) \u0026\u0026 $model-\u003esave()) {\n            return $this-\u003eredirect(['view']);\n        }\n\n        return $this-\u003erender('create', [\n            'model' =\u003e $model,\n        ]);\n    }\n\n    // ...\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Far-linkmany","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyii2tech%2Far-linkmany","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Far-linkmany/lists"}