model下的 link用法

平时开发中,我们经常会遇到相关联的表,一个表生成数据的同时,另外一个表也要同步插入数据。

表结构:

A表:account ,账户表
字段:id、username

B表:account_config , 账户配置表
字段:id、credit、aid(和A表的关联字段)

A表和B表的关联关系:a.id = b.aid

 

现在我们新建一个账户,同时生成对应的配置表。代码如下:

$trans = \Yii::$app->db->beginTransaction();
try {
    $account = new Account();
    $account->setAttributes(\Yii::$app->request->post(), false);
    if (!$account->save()) {
        throw new \Exception("账户生成失败", 10001);
    }

    $config = new AccountConfig();
    $config->credit = 100;
    $config->aid = $account->attributes['id'];
    if (!$config->save()) {
        throw new \Exception("配置生成失败", 10001);
    }
    echo "成功";
} catch (\Exception $e) {
    $trans->rollBack();
    echo "失败";
}

  

实际开发中,我们可能会遇到这种情况,最开始我们只有A表数据,而没有B表,后来在开发功能中,才新增加了B表。

一般情况下,我们创建B表时,就会通过脚本通过A表数据,初始化B表。但是假如我们现在不想通过初始化表的方法来填充B表呢。

而是我们访问A表记录时,查看B表是否有对应的数据,如果没有的话我们就在B表新增数据,代码如下:

A表对应的AR模型中新增代码:

    public static function findOrNewAccountConfig(ArAccountAR $model)
    {
        if(empty($model->payConfig)){
            $config = new AccountConfigAR([
                'id' => null,
                'aid' => $model->id,
                'password_enable' => 0,
                'credi' => 0,
            ]);
            //建立两个模型之间的关系,如果model 对那个的link 表没有数据,则会自动生成关联数据
            $model->link('payConfig', $config);
        }
        return $model->payConfig;
    }

    public function getAccoutConfig()
    {
        return $this->hasOne(AccountConfigAR::class, ['aid'=>'id']);
    }

  

控制器中的代码:

$id = 1;
$account = AccountAR::findOne($id);

//调用 AR 中的 findOrNewAccountConfig 方法,系统就会根据model生成关联的数据
//自动生成 account_config 表的数据
AccountAR::findOrNewAccountConfig($account);

 

 总结:以后遇到有关联表(依赖表)需要生成数据时,可以通过这种 findOrNewXxxx 的方法去实现。


 

 

yii获取刚插入的数据主键的方法:

单条数据时model->attributes['id'];
循环插入时使用 Yii::app()->db->getLastInsertID() 获取
循环插入时需要每次插入后重置
model->primarykey =0; 或 model->id = 0;
model->setIsNewRecord(true); 

  

posted on 2019-04-22 02:25  追风的浪子  阅读(516)  评论(0)    收藏  举报

导航