# 关于Yii2 model save方法的疑问

**URL:** <https://www.shiqidu.com/t/topic/452>\
**Category:** 开发调优\
**Tags:** Yii\
**Created:** [2018 年7 月 2 日 16:55 UTC](https://www.shiqidu.com/t/topic/452 "2018-07-02T16:55:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2018 年7 月 2 日 16:55 UTC](https://www.shiqidu.com/t/topic/452/1 "2018-07-02T16:55:05Z")

</div>

我有一段代码大致是这样的

```php
$model = new Notification();
if($type == 1) {
    $data = [];
    $data['aa'] = 1;
    $model->load($model, '') && $model->save();
}
if($count == 2) {
    $data = [];
    $data['bb'] = 2;
    $model->load($model, '') && $model->save();
}

```

这个时候$type = 1 , $count = 2 , 按照我的心里预期，应该是保存了两条数据，因为两条数据都符合条件，但是实际结果是只保存了最后一条数据。

如果想两条数据都保存，需要改成下面这样。

```php
$model = new Notification();
if($type == 1) {
    $data = [];
    $data['aa'] = 1;
    $_model = clone $model;
    $_model->load($model, '') && $_model->save();
}
if($count == 2) {
    $data = [];
    $data['bb'] = 2;
    $_model = clone $model;
    $_model->load($model, '') && $_model->save();
}

```

不知道为什么。下次写类似这种逻辑需要注意下。
