【问题标题】:Yii2 : To exclude an attribute in afterFind() functionYii2 : 在 afterFind() 函数中排除一个属性
【发布时间】:2018-01-04 13:18:43
【问题描述】:

我已经在 DB 中创建了_at 和 updated_at 列,我正在用时间戳填充它。

为了在 index.php 中显示 created_at 和 updated_at 日期(给 GridView 中的用户),我使用 Model 中的 afterFind 函数将时间戳转换为 YYYY-MM-DD 格式。

如果单击编辑按钮,我需要从 GridView 更新行中的状态。所以我在控制器中的代码是

$existingRow = Project::findOne($id) // From the parameter
$existingRow->status = 2
$existingRow->save()

在执行上述命令时,created_at 字段以“YYYY-MM-DD”格式保存,该格式由模型中的“afterFind()”函数转换而来。

如何获取未转换的时间戳值保存?

【问题讨论】:

  • 你为什么不在你的gridview上进行转换。这是最佳实践。
  • 我可以做到,而且会非常容易。但我想找到,控制器中有没有其他方法可以做到这一点。一些新代码可能会有所帮助。 :)

标签: php gridview yii yii2


【解决方案1】:

要处理created_atupdated_at,您应该使用TimestampBehavior。在您相应的模型中添加:

use yii\behaviors\TimestampBehavior;
public function behaviors()
{
    return [
        TimestampBehavior::className(),
    ];
}

然后它会在创建/更新模型时自动填写您的字段。

要在GridView 中正确显示它,请将您的列定义为:

<?= GridView::widget([
   'dataProvider' => $dataProvider,
   'columns' => [
       'id',
       'name',
       'created_at:datetime',    // or 'created_at:date' for just date
       // ...
   ],
]) ?>

afterFind() 不是解决此类问题的最佳方案。

【讨论】:

  • 我使用 beforeSave 函数代替了这个 TimestampBehavior 来获取当前时间戳。这是一个好习惯吗?。
  • 在这种情况下并非如此,特别是如果您有非常好的开箱即用解决方案。将代码调整为 TimestampBehavior 需要额外 5 分钟,但从长远来看是值得的。
  • 使用此 TimestampBehavior 工作正常,感谢您的回答。早些时候我们使用 beforeSave 和 afterFind 进行更改。 afterFind() 在我想写 API 时可能会有所帮助
【解决方案2】:

就像您覆盖 afterFind() 一样,您可以覆盖模型中的 beforeSave() 方法,以便在执行 Save 操作之前将属性重新格式化为所需的格式。

protected function beforeSave()
{
  $parentResult = parent::beforeSave();


  // pseudo code
  // Change any attributes values as you require
  // return true if successful ($result)

  return $parentResult && $result; // Save operation will run if this returns true only
}

【讨论】:

    【解决方案3】:

    这可能不是预期的答案,但这个功能让我得到了我想要的。使用 $model->getOldAttribute($attributeName) 给出数据库中的原始数据(即未经过 afterFind() 函数转换的原始数据)。

     $existingRow = ProjectResourceAssign::findOne($id);
     $existingRow->status = 2;
     // This piece of line will get you the original value of the attribute
     $existingRow->created_at = $existingRow->getOldAttribute('created_at');
     $existingRow->save(false);
    

    【讨论】:

    • 这是一个答案吗? (如果是,请解释它是如何解决问题的;如果不是,也许应该是对问题的编辑 - 使用问题下方的“编辑”按钮添加它)
    • 感谢您的建议。这是该问题的解决方案之一。我将在答案中添加详细信息。
    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2017-03-21
    • 2015-03-03
    相关资源
    最近更新 更多