udokmeci / yii2-closest-relation-trait
该特性添加了在不重新定义扩展关系的情况下获取最近相关模型类的能力。
Requires
- php: >=5.3.0
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2024-09-10 19:57:14 UTC
README
该特性添加了在不重新定义扩展关系的情况下获取最近相关模型类的能力。
为什么?
我喜欢使用 gii
,然而如果你像我一样经常更改表格,那么继续使用 gii
或手动添加更改将变得痛苦。
如果你使用 yii2
并与多个应用程序一起使用,那么在扩展模型时你必须移动关系。
这个特性(是的,我使用了特性而不是行为)添加了调用与模型及其父类共享命名空间的最接近类的能力。
例如,假设我们正在使用 yii2-advance-template
,所以我们可能有 3 个或更多同一类的子类。
调用类 Page
并关联到 Author
你可能拥有它在 common\models
、frontend\models
和 backend\models
中,所以如果你没有重写关系,你可能会通过 getter 获取 common\models\Author
。复制和粘贴关系很简单,但是将特性添加到你的基础模型中更容易。
如何使用?
## 使用 Composer 安装 仅需在您的 composer.json
文件中的 require
对象下添加一行。
{ "require": { "udokmeci/yii2-closest-relation-trait" : "dev-master" } }
然后运行
$> composer update
## 将特性添加到您的基模型。### 通过模型生成器 将以下 generators
数组添加到您的配置文件中。
$config['modules']['gii'] = [ 'class' => 'yii\gii\Module', 'generators' => [ 'model'=>'udokmeci\yii2closestrelation\model\Generator' ], ];
### 手动 只需在类中添加 use
语句,并从 static::getRelationName()
方法传递所有关系的 className
参数。以下是一个示例
<?php namespace common\models\base; use Yii; class Page extends \yii\db\ActiveRecord { //here is the trait and see also the relation use \udokmeci\yii2closestrelation\ClosestRelationTrait /** * @inheritdoc */ public static function tableName() { return 'page'; } /** * @return \yii\db\ActiveQuery */ public function getAuthor() { return $this->hasOne(static::getRelationName(Author::className()), ['author_id' => 'id']); } }
现在如果您既有 \frontend\models\Page
也有 \frontend\models\Author
关联,则返回 \frontend\models\Author
;如果没有两者,则再次返回 \common\models\base\Author
。
享受吧。