在Laravel 5中插入数据语句 - 一种更简洁的方式?

时间:2015-06-10 10:25:50

标签: php database laravel-5

遵循文档here中的约定,这是我的插入语句:

$input = Request::all();

DB::insert('
            insert into at (studentID, completedBy, timeStamp, contact, intervention, level, goal, access, recording, support, motivators, notes)
            values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [ $input['studentID'], $input['completedBy'], $input['timeStamp'], $input['contact'], $input['intervention'], $input['level'], $input['goal'], $input['access'], $input['recording'], $input['support'], $input['motivators'], $input['notes'] ]);

虽然它工作正常,但它似乎很愚蠢,因此难以复制具有不同值的其他表;是否有更简洁/更好的方式来构建声明?

1 个答案:

答案 0 :(得分:4)

如果您使用模型和Eloquent ORM,您可以使用create方法。

http://laravel.com/docs/5.1/eloquent#mass-assignment

如文档中所述,如果您有飞行模型(这将对应于数据库中的表格,例如flights

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];
}

然后,您可以在模型的create属性上调用$fillable方法,如下所示:

$flight = App\Flight::create(['name' => 'Flight 10']);

希望能让你开始。

我相信你的实现看起来像这样:

<强>模型

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class At extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'at'; // put your table name here

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'studentID',
        'completedBy',
        'timeStamp',
        'contact',
        'intervention',
        'level',
        'goal',
        'access',
        'recording',
        'support',
        'motivators',
        'notes',
    ];
}

插入

App\At::create([
    'studentID'    => $input['studentID'],
    'completedBy'  => $input['completedBy'],
    'timeStamp'    => $input['timeStamp'],
    'contact'      => $input['contact'],
    'intervention' => $input['intervention'],
    'level'        => $input['level'],
    'goal'         => $input['goal'],
    'access'       => $input['access'],
    'recording'    => $input['recording'],
    'support'      => $input['support'],
    'motivators'   => $input['motivators'],
    'notes'        => $input['notes'],
]);

我相信如果您的语句$input = Request::all();仅包含模型创建方法所需的值,您可能只能执行此操作:

$input = Request::all();

App\At::create($input);

没有['key' => 'value']