Search code examples
phparraysmodel-view-controllerquery-builderkohana

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


Hi folks! I'm trying to transfer data as array from the controller to the model, and then paste the data into the query builder, but the data must be in the same order as specified in the columns.

  • What options do I have?
  • And do you think this is a bad practice?

Controller:

            $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']
            ]);

Model:

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 ;
}

Solution

  • Thanks to this answer. Solved this by:

    // 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);