【问题标题】:Indirect modification of overloaded property to modify post data间接修改重载属性来修改post数据
【发布时间】:2017-11-03 11:56:24
【问题描述】:

我的目标是更改 $_POST['url'] 以将其保存在数据库中,前面带有“tcp://”.$_POST['url']。

$model = $this->loadModel($id);

if (isset($_POST['xxx'])) {     
    $model->attributes = $_POST['xxx'];
    $model->attributes['url'] = 'tcp://'.$_POST['xxx'];  <-
    if ($model->save()) {

但它返回“间接修改重载属性”。 更改该字段的正确方法是什么?

【问题讨论】:

  • 你可以做到 $model->ur = 'tcp://'.$model->ur

标签: forms yii


【解决方案1】:

在这种情况下,您有两个选择:

1) 因为您使用了$model-&gt;attributes = $_POST['xxx'];,所以您可以访问$_POST['xxx'] 中的值作为模型的属性,因此$model-&gt;url = 'something'; 将起作用。

2) 通常,您可以将要修改的值移动到新变量中,在那里修改它们并用新变量覆盖原始值。如果您想修改相关模型,这会特别有用,这会导致您收到相同的错误消息。

错误的方式:

$model->relationSomething = new RelationSomething;
$model->relationSomething->someAttribute = 'newValue';

上面的代码将导致您收到错误消息。

正确方法:

$model->relationSomething = new RelationSomething;
$tempVariable = $model->relationSomething;
$tempVariable->someAttribute = 'newValue';
$model->relationSomething = $tempVariable;
//Optimally you want to save the modification

使用此方法可以让您修改相关模型中的属性而不会导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2020-03-24
    • 2011-07-17
    • 1970-01-01
    相关资源
    最近更新 更多