如果您想让中间表自动维护 created_at 和updated_at 时间戳,那么在定义关联时加上 withTimestamps 方法即可。return $this->belongsToMany('App\Role')->withTimestamps(); 通过中间表过滤关联数据在定义关联时,您可以使用 wherePivot 和wherePivotIn 方法过滤 belongsToMany 返回的结果:...
你可以使用attach方法来附加一个角色到用户并且在中间表中加入这条记录: $user = App\User::find(1); $user->roles()->attach($roleId); 当附加关联到模型时,你也可以传递一个含有额外数据的数组来将其添加到中间表中: $user->roles()->attach($roleId, ['expires' => $expires]); 当然,有时候你可...
$roleID= 1;$user->roles()->attach($roleID); AI代码助手复制代码 默认情况下,这个中间表不包含时间戳。并且 Laravel 不会尝试自动填充 created_at/updated_at 但是如果你想自动保存时间戳,您需要在迁移文件中添加 created_at/updated_at,然后在模型的关联中加上 ->withTimestamps(); publicfunction roles(...
return $this->belongsToMany('App\Role')->withPivot('foo', 'bar'); 现在可以在 Role 模型的 pivot 对象上取得 foo 和bar 属性了。如果您想要可以自动维护枢纽表的 created_at 和updated_at 时间戳,在定义关联方法时加上 withTimestamps 方法:...
$roleID= 1;$user->roles()->attach($roleID); 默认情况下,这个中间表不包含时间戳。并且Laravel不会尝试自动填充created_at/updated_at 但是如果你想自动保存时间戳,您需要在迁移文件中添加created_at/updated_at,然后在模型的关联中加上->withTimestamps(); ...
$user->roles()->attach($roleID); 默认情况下,这个中间表不包含时间戳。并且Laravel不会尝试自动填充created_at/updated_at 但是如果你想自动保存时间戳,您需要在迁移文件中添加created_at/updated_at,然后在模型的关联中加上->withTimestamps();
return $this->belongsToMany('App\Role')->withPivot('foo', 'bar');Copy現在可以在 Role 模型的 pivot 物件上取得 foo 和bar 屬性了。如果想要可以自動維護樞紐表的 created_at 和updated_at 時間戳,在定義關聯方法時加上 withTimestamps 方法:return $this->belongsToMany('App\Role')->withTimestamp...
return $this->belongsToMany('App\Role')->withTimestamps();Copy自訂pivot 屬性名稱如之前所說的,從中介表中的數行可以在模型上使用 pivot 方法來存取。然而,你可以自由的自訂該屬性的名稱來更好的反映在應用程式中的用途。例如,如果你的應用程式包含可以訂閱 Podcasts 的使用,使用者與 Podcasts 之間可能存在...
如果你想要中间表自动维护created_at和updated_at时间戳,你可以在定义关联时使用withTimestamps方法: return $this->belongsToMany("AppRole")->withTimestamps(); 通过中间表字段过滤关系 你可以通过在定义关联时使用wherePrivot和wherePivotIn方法来在返回的结果中进行过滤: ...
return $this->belongsToMany('Role')->withTimestamps(); 删除枢纽表的关联数据要删除模型在枢纽表的所有关联数据,可以使用 detach 方法:User::find(1)->roles()->detach(); 注意,如上的操作不会移除 roles 数据库表里面的数据,只会移除枢纽表里的关联数据。