简体   繁体   English

每当在 laravel 中发生记录插入或更新时,在 pivot 表中设置一个字段

[英]set a field in pivot table whenever a record insert or update happens in laravel

OK, recently I am implementing an RBAC based system in laravel.好的,最近我在 laravel 中实现了一个基于 RBAC 的系统。

I have these two classes as my models:我有这两个类作为我的模型:

class User extends Authenticatable
{
    public function roles(){
        return $this->belongsToMany(\App\Role::class, 'user_role', 'user_id', 'role_id')->withPivot('is_expired', 'assigned_at', 'expire_at');
    }
}

class Role extends Model
{
    public function users(){
        return $this->belongsToMany(\App\User::class, 'user_role', 'role_id', 'user_id')->withPivot('is_expired', 'assigned_at', 'expire_at');
    }
}

it works fine BUT, I want to set a default value for the expire_at attribute of the pivot table based on an attribute of the Role model.它工作正常但是,我想根据Role model 的属性为 pivot 表的expire_at属性设置默认值。 for example I have a period attribute on Roles table, and its a number representing number of months.例如,我在Roles表上有一个period属性,它是一个代表月数的数字。 So i want when a role assigned to a user (inserted in pivot table) the value of expire_at set to currentDatetime + thePeriodNum months and save in the pivot table.因此,我希望当分配给用户的角色(插入 pivot 表中)将expire_at的值设置为currentDatetime + thePeriodNum月并保存在 pivot 表中。

how can I achieve this?我怎样才能做到这一点?

I have tried laravel custom pivot class and mutators but it seems not working or I did something wrong.我已经尝试过 laravel 自定义 pivot class 和突变器,但它似乎不起作用或者我做错了什么。 somebody mentioned that the mutators dont get triggered when using attach() / detach() methods so I think even if it was working i could not see the difference.有人提到使用attach() / detach()方法时不会触发突变器,所以我认为即使它正在工作,我也看不出有什么区别。 Someone mentioned its possible with observers but I have no Idea what is an observer im noob.有人提到了观察者的可能性,但我不知道什么是观察者我是菜鸟。

So thats all, it would be really good for me if anybody could help me through this mess I'm in right now.就是这样,如果有人能帮助我度过我现在所处的这个烂摊子,那对我来说真的很好。 Thanks in advance.提前致谢。

It is possible to attach the new role and set the expires_at column at the same time.可以同时附加新角色并设置expires_at列。 This would avoid needing to use observers (listeners of model events) within your code.这将避免在您的代码中使用观察者(model 事件的侦听器)。

The code would look like the following:代码如下所示:

$role = Role::find($roleId);

$expireAt = now()->addMonths($role->period)->toDateTimeString();

// or Carbon::now()->addMonths($role->period)->toDateTimeString();

User::find($userId)->roles()->attach($role->id, ['expire_at' => $expireAt]);

Here, the role is found.在这里,找到了角色。 A timestamp is created by taking the current time, adding the addition months based on the role's period (this should be an integer value).通过获取当前时间创建时间戳,根据角色的period添加额外的月份(这应该是 integer 值)。

Finally, this is added to the attachment of the role to the user.最后,将其添加到用户的角色附件中。

Add as a model method添加为 model 方法

This can all be added as a function/method on the User model which would clean up the code into one action, ->addRole($roleId) :这都可以作为函数/方法添加到User model 上,这会将代码清理为一个操作->addRole($roleId)

// Within App\User.php

public function addRole($roleId)
{
    $role = \App\Role::find($roleId);

    $expiresAt = now()->addMonths($role->period)->toDateTimeString();

    $this->roles()->attach($role->id, [ 'expire_at' => $expiresAt ]);
}

This can then be called with the following:然后可以使用以下方法调用它:

$user = User::find($id);

$user->addRole($roleId);

I hope this help.我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM