Laravel 的 updateOrCreate 中的 created_by 和 updated_by

Her*_*oko 2 laravel eloquent

使用"updateOrCreate"命令,我们如何"created_by"在插入新行时更新,

并在更新"updated_by"时更新?

$flight = App\Flight::updateOrCreate(
   [   
       'departure' => 'Oakland', 
       'destination' => 'San Diego'
   ],
   [
      'price' => 99,
      'created_by' => $user_id,
      'updated_by' => $user_id,
   ]
);
Run Code Online (Sandbox Code Playgroud)

Sok*_*nty 7

class Model extend Model {
     public static function boot()
     {
        parent::boot();
        static::creating(function($model)
        {
            $user = Auth::user();           
            $model->created_by = $user->id;
            $model->updated_by = $user->id;
        });
        static::updating(function($model)
        {
            $user = Auth::user();
            $model->updated_by = $user->id;
        });       
    }
}
Run Code Online (Sandbox Code Playgroud)


Nik*_*hod 5

您可以尝试以下解决方案来解决您的问题:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class Flight extends Model {

    use SoftDeletes;
    use Notifiable;

    /**
     * Table name
     * @var variable
     */
    public $table = 'flight';

     /**
     * For Soft delete
     * @var array
     */
    protected $dates = ['deleted_at'];

    protected static function boot() {
        parent::boot();

        static::creating(function ($model) {
            $model->created_by = is_object(Auth::guard(config('app.guards.web'))->user()) ? Auth::guard(config('app.guards.web'))->user()->id : 1;
            $model->updated_by = NULL;
        });

        static::updating(function ($model) {
            $model->updated_by = is_object(Auth::guard(config('app.guards.web'))->user()) ? Auth::guard(config('app.guards.web'))->user()->id : 1;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这会有帮助的。谢谢!!