ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 라라벨에서 다대다 다형 관계 구현하기: 유연성과 코드 재사용성
    백엔드/laravel 2024. 1. 27. 19:06

     

    다대다 다형 관계를 사용하는 이유 중 하나는 유연성입니다.

    이 관계를 사용하면 전통적인 다대다 관계로는 만들기 어려웠거나 불가능했던 복잡한 데이터 구조를 만들 수 있습니다.

    또한 코드 재사용성 때문입니다.

    다형 관계를 생성하면 코드를 여러 모델에서 중복으로 작성하는 대신 여러 모델에서 코드를 재사용할 수 있습니다.

     

    예를 들어, 포스트, 비디오 및 태그라는 세 가지 모델이 있는 웹 애플리케이션을 고려해 봅시다.

    포스트 및 비디오 모델은 각각 여러 태그를 가질 수 있으며 각 태그는 여러 포스트 및 비디오와 관련될 수 있습니다.

     

    태그 포스트와 비디오 모델 사이에 다대다 다형성 관계를 설정하기 위해 Taggable 모델 생성합니다.

     

     php  artisan make:model Taggable -m;

     

    app\Models\Taggable.php

    ---------------------------

    class Taggable extends Model
    {
        use HasFactory;
    }

     

    Tag 모델 작성

    class Tag extends Model
    {
        public function taggables(): MorphToMany
        {
            return $this->morphToMany(related: Taggable::class, name: 'taggables');
        }
    }

     

    Post 모델 작성

    class Post extends Model
    {
        public function tags(): MorphToMany
        {
            return $this->morphToMany(related: Tag::class, name: 'taggable');
        }
    }

     

     

     php artisan Tinker;

    --------------------

    $post = Post::find(5);
    = App\Models\Post {#5955
        id: 5,
        user_id: 6,
        slug: "enim-facere-quia-eos-suscipit",
        excerpt: "Sunt iusto asperiores ab id.",
        description: "Et est omnis fugit beatae hic et.",
        is_published: 0,
        min_to_read: 5,
        created_at: "2024-01-14 01:30:46",
        updated_at: "2024-01-14 01:30:46",
      }

    > $tagIds = [1,2,3];
    > $post->tags()->attach($tagIds);

     

    > $video = Video::find(1);
    = App\Models\Video {#5964
        id: 1,
        title: "외계인1",
        url: "i dont",
        description: "big fun",
        created_at: "2024-01-27 07:09:14",
        updated_at: "2024-01-27 07:09:14",
      }

    > $video->tags()->attach($tagIds);

     

    attach 메서드를 사용하여 다대다 관계를 설정합니다. $tagIds 배열에 있는 태그 ID들이 Post 게시물과 연결됩니다.

    Laravel에서 다대다 다형 관계를 설정하는 경우 attach 메서드를 사용하여 관계를 설정할 수 있습니다.

    이는 다수의 모델 간의 복잡한 관계를 쉽게 설정할 수 있는 강력한 방법 중 하나입니다.

     

     

    taggables table 결과

    ------------------------

    1 1 5 App\Models\Post
    2 2 5 App\Models\Post
    3 3 5 App\Models\Post
    4 1 1 App\Models\Video
    5 2 1 App\Models\Video
    6 3 1 App\Models\Video

    댓글

Designed by Tistory.