Laravel:定义多对多关联的反向User模型实现
Laravel 多对多关联:User 模型关联方法补充
从你给出的 Group 模型代码来看,这是**多对多(Many-to-Many)**关联关系——一个组可以拥有多个用户,同时一个用户也可以属于多个组。
因此 User 模型的关联方法也应该使用 belongsToMany,而非一对多关联的 belongsTo。按照你提供的模型框架,修改后的代码如下:
class User extends Model { /** * The groups that the user belongs to. */ public function group() { return $this->belongsToMany(Group::class)->withTimestamps(); } }
补充说明
- 多对多关系的双向定义都需要使用
belongsToMany方法 withTimestamps()会让 Laravel 自动维护中间表的created_at和updated_at字段- 建议将方法名改为复数形式
groups(),更符合「一个用户可属于多个组」的语义,修改后代码如下:
class User extends Model { /** * The groups that the user belongs to. */ public function groups() { return $this->belongsToMany(Group::class)->withTimestamps(); } }
内容的提问来源于stack exchange,提问作者DevonDahon
相关产品推荐
相关产品推荐

