Array to DB::insert()->values(),与列顺序不同

Array to DB::insert()->values(), which is in different order with the columns

大家好! 我正在尝试将数据作为数组从 controller 传输到 model,然后将数据粘贴到 查询构建器 ,但数据的顺序必须与列中指定的顺序相同。

控制器:

            $responseNotes = Model::factory('Notes')-> createTicket([
                'description'   => htmlspecialchars($_POST['description']),
                'contact_id'    => $_POST['contact_id'],
                'pref_contact'  => $_POST['pref_contact'],
                'dog_id'        => $_POST['document_id'],
                'type'          => $_POST['type'],
                'owner_id'      => Auth::instance()->get_user()->id,
                'cc'            => $_POST['cc-emails'],
                'title'         => $_POST['title']
            ]);

型号:

public function createNote(array $data)
{
    $columns = [
        'type',
        'owner_id',
        'cc',
        'title',
        'description',
        'contact_id',
        'pref_contact',
        'dog_id'
    ];
    if (!array_diff($columns, array_keys($data))) {
        // All needed values exists
        $result = DB::insert($this->NOTES, $columns)-> values($data)-> execute($this->SCHEMA);
    }
    return  ($result) ? $result : false ;
}

感谢this answer。解决方法:

// Order $data array according to $column.values
$orderedData = [];
foreach ($columns as $key) {
    $orderedData[$key] = $data[$key];
}
$result = DB::insert($this->TICKETS, $columns)
    -> values($orderedData)
    -> execute($this->SCHEMA);

为什么不使用 ORM Model

在控制器中:

$responseNotes = ORM::factory('Notes')-> values([
                'description'   => htmlspecialchars($_POST['description']),
                'contact_id'    => $_POST['contact_id'],
                'pref_contact'  => $_POST['pref_contact'],
                'dog_id'        => $_POST['document_id'],
                'type'          => $_POST['type'],
                'owner_id'      => Auth::instance()->get_user()->id,
                'cc'            => $_POST['cc-emails'],
                'title'         => $_POST['title']
            ])
try{
   $responseNotes->save();
} catch (ORM_Validation_Exception $ex) { 
   print_r($ex->errors('models'));
}

并且不要使用 htmlspecialchars($_POST['description'])

在模型class中修改函数(doc):

public function filters()
{
    return array(
      'description' => array( array('htmlspecialchars') ),
    );
}

看起来您的关联数组结构 db_column=>value 对吗?比你可以像这样简单地插入:

DB::Insert('table_name',array_keys($data))->values(array_values($data))->execute();