Laravel 5 insert 在没有 $fillable 的情况下有效

Laravel 5 insert works without $fillable

我有一个 Laravel 别人的申请。

在控制器中我有这个:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Result;

class StoreInDB extends Controller
{
    function store($uuid, $session){
        // Insert data
        $r = new Result;
        if($r->updateOrInsert(['user_id' => $uuid], ['user_id' => $uuid, 'answers' => $session])){
            return true;
        }
        else{
            return false;
        }
    }
}

在模型结果中我有这个:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Result extends Model
{
    //
}

为什么有效?没有$fillable 告诉哪一列可以用来插入。

数据已插入。但为什么?我遇到的唯一问题是 created_at 和 updated_at 为空。

updateOrInsert 使用查询生成器而不是 eloquent,因此它不会触发模型事件或遵守 guardedfillable 属性,也不会填充 created_atupdated_at 列。

如果您想使用提到的 eloquent 功能,您应该使用 updateOrCreate

像这样:

public function store($uuid, $session)
{
    if (null === Result::updateOrCreate(['user_id' => $uuid], ['answers' => $session])) {
        return false;
    }

    return true;
}

请注意 updateOrCreate returns 一个模型实例和 updateOrInsert returns 一个 boolean.

updateOrCreate:

Occasionally, you may need to update an existing model or create a new model if no matching model exists. Like the firstOrCreate method, the updateOrCreate method persists the model, so there's no need to manually call the save method.

In the example below, if a flight exists with a departure location of Oakland and a destination location of San Diego, its price and discounted columns will be updated. If no such flight exists, a new flight will be created which has the attributes resulting from merging the first argument array with the second argument array:

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

updateOrInsert:

Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.

The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments:

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );