【问题标题】:Maintain an updated_by field by using through model Laravel通过模型 Laravel 维护一个 updated_by 字段
【发布时间】:2018-09-13 13:01:03
【问题描述】:

我无法弄清楚这个模型有什么问题,我似乎使用相同的方法通过使用相同的方法来更新“updated_by”字段。这是我的模型地址代码。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;


class Address extends Model
{
    //declare table since we not generate it using migrate laravel 
    protected $table = 'ADDRESS';

    //assign all field as fillable
    protected $guarded = [];

    // Update field update_by for Address .
    public static function boot()
    {

    //this function not work when updating
    static::updating(function ($Address) {
        $Address->created_by = Auth::user()->id;
    });

    //this function work perfectly 
    static::creating(function ($Address) {
        $Address->updated_by = Auth::user()->id;
        $Address->created_by = Auth::user()->id;
    });

}


function getMember()
{
    return $this->belongsTo('App\Mbrdata','mbr_id');
}
}

此代码在其他模型上完美运行,不知何故对于这个模型它不做任何事情。生病尝试跟踪错误,不知何故我不知道如何调试错误,因为我没有看到任何错误/异常消息。任何建议如何调试此类问题?因为我检查了我的日志,所以也没有记录任何错误。

更正:-

    public static function boot()
{

    //this function not work when updating
    static::updating(function ($Address) {
        $Address->updated_by = Auth::user()->id;
    });

    //this function work perfectly 
    static::creating(function ($Address) {
        $Address->updated_by = Auth::user()->id;
        $Address->created_by = Auth::user()->id;
    });

}

但是在更正之后仍然相同,该字段仍然没有更新为当前用户。

【问题讨论】:

  • 当通过 Eloquent 发布大规模更新时,已保存和更新的模型事件不会为更新的模型触发。这是因为在发布大规模更新时从未真正检索到模型。检查文档
  • 这可能只是您的问题中的一个错字,但您的updating() 事件方法正在更新created_by 字段,而不是updated_by 字段。
  • 对不起我的错字,实际上已经做了另一个,没关系,只是这个我不知道原因在哪里。
  • 如何更新模型?顺便说一句:boot() 应始终以 parent::boot(); 开头。

标签: laravel model eloquent


【解决方案1】:

您在更新方法中使用created_by字段应该有updated_by

你可以试试这个,也许对你有帮助

public static function boot()
{

    //this function not work when updating
    static::updated(function ($Address) {
        $Address->updated_by = Auth::user()->id;
    });

    //this function work perfectly 
    static::creating(function ($Address) {
        $Address->updated_by = Auth::user()->id;
        $Address->created_by = Auth::user()->id;
    });

}

试试上面的,如果有帮助,请告诉我。

【讨论】:

    猜你喜欢
    • 2015-02-12
    • 2019-09-30
    • 1970-01-01
    • 2014-04-02
    • 2014-05-06
    • 2016-11-04
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多