Laravel 개발: Laravel Eloquent를 사용하여 다형성 연관을 구현하는 방법은 무엇입니까?
다형성 연관은 Laravel Eloquent의 중요한 기능으로, 하나의 모델이 여러 다른 모델과 관계를 설정할 수 있게 해줍니다. 실제 응용 프로그램에서 다양한 유형의 데이터를 처리하는 것은 특히 데이터베이스 설계에서 상대적으로 간단하고 효율적입니다. 이 글에서는 Laravel Eloquent를 사용하여 다형성 연관을 구현하는 방법에 대해 설명합니다.
1. 다형성 연관이란 무엇인가요?
다형성 연관은 여러 다른 모델과 연관 관계를 설정하는 모델을 말하며, 이는 일반 범주에 대한 참조로 간주될 수 있습니다.
2. 다형성 연관 구현 방법
Laravel Eloquent를 사용하여 다형성 연관을 구현하는 방법을 살펴보겠습니다.
우선 데이터 테이블의 디자인을 고려해야 합니다. 모델 간의 다형성 관계를 저장하려면 중간 테이블을 만들어야 합니다. 이 테이블에는 다음 열이 포함되어야 합니다.
<?php use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class CreateCommentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('comments', function (Blueprint $table) { $table->id(); $table->morphs('commentable'); $table->text('content'); $table->timestamps(); }); Schema::create('votes', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('voteable_id'); $table->string('voteable_type'); $table->enum('type', ['up', 'down']); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('comments'); Schema::dropIfExists('votes'); } }
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Comment extends Model { use HasFactory; public function commentable() { return $this->morphTo(); } public function votes() { return $this->morphMany(Vote::class, 'voteable'); } }
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Vote extends Model { use HasFactory; public function voteable() { return $this->morphTo(); } public function user() { return $this->belongsTo(User::class); } }
$article = Article::find(1); $comment = $article->comments()->create([ 'content' => 'This is a comment', ]);
$votes = $comment->votes;
$comments = $article->comments;
$comment->votes()->create([ 'user_id' => 1, 'type' => 'up', ]);
위 내용은 Laravel 개발: Laravel Eloquent를 사용하여 다형성 연관을 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!