【问题标题】:Do something before saving model to database in Laravel 5.1在 Laravel 5.1 中将模型保存到数据库之前做一些事情
【发布时间】:2015-08-13 16:19:44
【问题描述】:

在将数据写入 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))

我该如何解决?

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:
    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;
        }
    }
    

    【讨论】:

    • 我已经展示了我的代码。它看起来非常接近您的代码,但它不起作用。
    • @ronin1184 - Atoken::insert($params) 不使用该模型。请改用create。我已将您的 newToken 方法添加到我的答案中。
    • 非常感谢。有效。顺便说一句,请解释一下为什么“插入”不是“创建”使用模型?
    • Insert 被转换成纯 SQL-insert 语句,当 create 采用 laravel-eloquent 方式时。
    【解决方案2】:

    我会建议进入 EventServiceProvider,并注册事件监听器

    public function boot(DispatcherContract $events)
        {
            parent::boot($events);
    
            // Register Event Listeners
            \App\Product::updating(function ($product) {
                $product->onUpdating();
            });
    ...
    

    然后在模型中创建函数onUpdating。你也可以选择saving, saved, creating, created, updating, updated..

    这个文档有更多: https://laravel.com/docs/5.1/eloquent#events

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多