在Laravel中,模型關系可以通過定義模型之間的關聯方法來實現。以下是幾種常見的模型關系及其定義方法:
class User extends Model
{
public function phone()
{
return $this->hasOne(Phone::class);
}
}
class Phone 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);
}
}
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
class User extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
通過定義以上關聯方法,可以在模型之間建立相應的關系,方便進行數據查詢和操作。