简体   繁体   English

在Datamapper ORM中循环更改对象

[英]changing object in loop in Datamapper ORM

I'm trying to save a long form in Codeigniter's Datamapper. 我正在尝试在Codeigniter的Datamapper中保存一个长格式。 I'm able to save the form if I pass the value like this 如果我传递这样的值,我就能保存表格

$t->brandName = $this->input->post('brandName');  
$t->specialNotes = $this->input->post('specialNotes');
$t->name = $this->input->post('name');

Now if I call save method it works 现在,如果我调用保存方法,它将起作用

 $t->save();

Since the form is big I tried to add object values in foreach 由于形式很大,我试图在foreach中添加对象值

 $a = get_object_vars($t);
 foreach ($a['stored'] as $k => $val){
      $t->$k = $this->input->post("$k"); 
 }

however if I call the $t->save() it doesn't work. 但是,如果我调用$t->save()它将不起作用。

I'm not sure what $a['stored'] represents, but it's nothing that's default in Datamapper. 我不确定$a['stored']代表什么,但这并不是Datamapper的默认设置。

Why don't you do it the opposite way, looping through the post keys? 为什么不按相反的方式循环遍历发布键?

foreach ($_POST as $key => $val)
{
    $t->$key = $this->input->post($key); 
}
$t->save();

Note: Any columns that don't exist will just be ignored by Datamapper. 注意:任何不存在的列都将被Datamapper忽略。


I actually wrote a Datamapper extension for this: 我实际上为此编写了一个Datamapper扩展:

class DM_Data {

    function assign_postdata($object, $fields = NULL)
    {
        // You can pass a different field array if you want
        if ( ! $fields)
        {
            $fields = $object->validation;
        }
        foreach ($fields as $k => $data)
        {
            $rules = isset($data['rules']) ? $data['rules'] : array();

            if ( ! isset($_POST[$k])) continue;

            // Cast value to INT, usually for an empty string.
            if (in_array('integer', $rules))
            {
                $object->$k = (integer) $_POST[$k];
            }
            // Do other manipulation here if desired
            else
            {
                $object->$k = $_POST[$k];
            }

        }
        return $object;
    }

}

You can use $t->assign_postdata()->save() , and optionally pass an array of fields to update to the function (in the datamapper validation format). 您可以使用$t->assign_postdata()->save() ,还可以选择传递一个字段数组以更新到函数(以datamapper验证格式)。 However, I forget why I use that... but I removed some of the custom stuff. 但是,我忘记了为什么要使用它...但是我删除了一些自定义内容。 This should be useful for you if you are doing this a lot. 如果您经常这样做,这对您很有用。 It definitely saves me time. 绝对可以节省我的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM