使用"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)
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)
您可以尝试以下解决方案来解决您的问题:
<?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)
这会有帮助的。谢谢!!
| 归档时间: |
|
| 查看次数: |
1824 次 |
| 最近记录: |