Полиморфные отношения
Один к одному (полиморфное)

public function imageable()
{
return $this->morphTo();
}
public function image()
{
return $this->morphOne(Image::class, 'imageable');
}
public function image()
{
return $this->morphOne(Image::class, 'imageable');
}
Создание отношений «Один-к-Одному» (полиморфное)
// выбираем пост с айди 1
$post = Post::find(1);
// создаём изображение
$image = new Image([
'url' => 'some image url'
]);
// связываем наше изображение с постом и сохраняем его
$image->imageable()->associate($post);
$image->save();
Отсоединение связи «Один-к-Одному» (полиморфное)
$post = Post::find(1);
$image = Image::find(1);
// отсоединяем imageable(post/user) от изображения и сохраняем его
$image->imageable()->dissociate($post);
$image->save();
Получение данных «Один-к-Одному» (полиморфное)
// выбираем пост с айди 1
$post = Post::find(1);
// получаем его image
$image = $post->image;
// выбираем изображение с айди 1
$image = Image::find(1);
// получаем его imageble (post/user)
$imageable = $image->imageable;
Удаление данных «Один-к-Одному» (полиморфное)
// выбираем пост с айди 1
$post = Post::find(1);
// удаляем пренадлежащее ему изображение
$post->image()->delete();
Один ко многим (полиморфное)

public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function commentable()
{
return $this->morphTo();
}
Многие ко многим (полиморфное)

public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
public function videos()
{
return $this->morphedByMany(Video::class, 'taggable');
}
Last updated