Laravel 5.4 Eloquent不保存某些字段

时间:2017-06-05 10:14:19

标签: laravel eloquent observers

我一直在努力记录模型事件中的所有用户活动......但由于某种原因,记录存储在user_action表中,但存储在action_model字段中。这是我的代码。 用户操作类 `

class UserAction extends Model
{

  use SoftDeletes;

  protected $table = 'user_actions';

  /**
  *
  */

  protected $fillable = [
      'user_id','action', ' action_model', 'action_id'
  ];

  public function user()
  {
      return $this->belongsTo(User::class, 'user_id');
  }



}

`

UserActionObervable

    class UserActionObserver
{
    public function saved($model)
    {
        $type = $model->getTable();
        // dd($type); when dump the value exists
        if ($model->wasRecentlyCreated == true) {
            // Data was just created
            $action = 'created';
        } else {
            // Data was updated
            $action = 'updated';
        }
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => $action,
                'action_model' => 'model', //I tried to pass in constant
                'action_id'    => $model->id
            ]);
        }
    }

    public function deleting($model)
    {
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => 'deleted',
                'action_model' => $model->getTable(),
                'action_id'    => $model->id
            ]);
        }
    }
}

这是架构

Schema::create('user_actions', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('user_id')->unsigned()->nullable();
      $table->string('action');  // created / updated / deleted
      $table->string('action_model');
      $table->integer('action_id')->nullable(); 
      $table->timestamps();

      $table->engine = 'InnoDB';
      $table->foreign('user_id')->references('id')
            ->on('users')->onDelete('cascade');

    });

1 个答案:

答案 0 :(得分:4)

protected $fillable = [
    'user_id','action', ' action_model', 'action_id'
];

尝试删除action_model之前的空格。 $fillable中的字段与您传递到create()方法的密钥不匹配。