我有三个数据库表,名为 user(id,name)、group(id,name) 和 user_group(user_id, group_id,valid_before),具有多对多关系。
class User extends Model
{
protected $table = 'user';
public function groups()
{
return $this->belongsToMany(Group::class, 'user_group')
->withPivot('valid_before');
}
}
class Group extends Model
{
protected $table = 'group';
public $timestamps = false;
public function user()
{
return $this->belongsToMany(User::class, 'user_group');
}
}
在“valid_before”时刻之前,用户可以是某个组的成员。如果“valid_before”小于当前时间,则必须将用户从组中排除,并且必须删除数据透视表中的相应行。如何在数据透视表中选择 strtotime($validBefore) < strtotime($date) 的行,然后使用 Eloquent 删除它们?
最佳答案
使用 cronjob 然后简单地使用 detach($group_id)
如下所示:-
$user = User::find($id);
if(time_exceeded($user->id)) //checks if user should stay in a group
$user->groups()->detach($group_id);
使用这个link供引用
关于laravel-5 - Laravel Eloquent 如何选择和操作数据透视表中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58023722/