https://laravelacademy.org/post/9584.html
一对一:
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
一对多:
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
} }
class Comment extends Model {
public function post() {
return $this->belongsTo(Post::class);
} }
多对多:
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}