gpt4 book ai didi

laravel - 在 Laravel 5.1 中将模型保存到数据库之前做一些事情

转载 作者:行者123 更新时间:2023-12-04 17:17:38 27 4
gpt4 key购买 nike

在将数据写入 Laravel 5.1 模型中的数据库之前,我该如何做一些事情,例如修改某些数据字段或进行更多验证?
有关该问题的文档在实际应用中很难使用:http://laravel.com/docs/5.1/eloquent#events

我的代码是

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Helpers\Tools as Tools;

class Atoken extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'atoken';

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'token',
'user_id',
'role',
];

/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];

public static function newToken($userId, $role){
# Remove all token assoiciate with input user;
Atoken::where('user_id', $userId)->delete();
$params = [
'user_id' => $userId,
'role' => $role,
];
Atoken::insert($params);
$item = Atoken::where('user_id', $userId)->first();
return $item->token;
}

protected static function boot(){
static::creating(function ($model) {
$model->token = 'sometoken';
});
}
}

在这种情况下,我总是遇到错误:
SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"token\" violates not-null constraint (SQL: insert into \"atoken\" (\"user_id\", \"role\") values (2, USER))

我该如何解决?

最佳答案

class Lunch extends Eloquent
{
protected static function boot()
{
static::creating(function ($model) {
$model->topping = 'Butter';

return $model->validate();
});
}

protected function validate()
{
// Obviously do real validation here :)
return rand(0, 1) ? true : false;
}

public static function newToken($userId, $role)
{
static::where('user_id', $userId)->delete();

return static::create([
'user_id' => $userId,
'role' => $role,
])->token;
}
}

关于laravel - 在 Laravel 5.1 中将模型保存到数据库之前做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31993559/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com