【问题标题】:How to get model attribute name based on id using Spatie/Activitylog?如何使用 Spatie/Activitylog 根据 id 获取模型属性名称?
【发布时间】:2019-08-19 06:54:31
【问题描述】:

我正在尝试使用 Spatie/Activitylog activity_log 表的属性属性基于 Task 模型的 employee_id 获取员工姓名。

我的模特:

use LogsActivity;

    protected $fillable = ['id','employee_id', 'name', 'description'......];

    protected static $logAttributes = ['id','employee_id','name', 'description'......];

    protected static $logFillable = true;
    protected static $logUnguarded = true;

我的控制器:

    {
        $activity = Activity::orderBy('id', 'DESC')->paginate(15);

        return view('adminlte::home', ['activity' => $activity]);
    }

我的刀片:

@foreach($activity as $act)

  {{$act->changes['attributes']['employee_id']}}

@endforeach

属性字段中保存的记录:

{"attributes":{"id":170,"employee_id":"[\"1\",\"2\"]","name":"test","description":"test",......}}

另外,在我的刀片中,结果是:

|employee_id | name       | description| ...
|------------|------------|------------|--------
|["1","2"]   | test       | test       | ....

问题是,如何根据employee_id 获取Name 字段。例如在本例中,Jon, David(不是他们的 ID(["1","2"])。所以,我想获取名称而不是 ID。

提前谢谢你。

【问题讨论】:

    标签: arrays laravel model activitylog


    【解决方案1】:

    我会从数据库中获取它们

    1) 创建一个 id 列表并获取它们。

    $employees = Employee::whereIn('id', $activity->pluck('employee_id')->flatten())
        ->get()
        ->mapWithKeys(function ($employee) {
            return [$employee->id => $employee];
        });
    

    2) 发送到前端

    return view('adminlte::home', ['activity' => $activity, 'employees' => $employees]);
    

    3) 使用映射来显示名称

    @foreach($activity as $act)
         @foreach($act->changes['attributes']['employee_id'] as $employeeId)
              {{ $employees[$employeeId] }}, 
         @endforeach
    @endforeach
    

    【讨论】:

    • 我收到一个错误:Invalid argument supplied for foreach()
    • Activity模型是否包含$casts数组$casts = ['employee_id' => 'json'];
    猜你喜欢
    • 2021-03-09
    • 2018-07-04
    • 2015-10-26
    • 2011-07-27
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    相关资源
    最近更新 更多