programing

해외이주의 핵심과 라라벨에서의 웅변적 관계

cafebook 2023. 9. 10. 12:39
반응형

해외이주의 핵심과 라라벨에서의 웅변적 관계

Laravel 5.1에서 테이블 열 관계는 다음과 같은 두 가지 방법으로 설정할 수 있음을 알 수 있습니다.

1) 마이그레이션 테이블에서 외부 키를 정의하고 있습니다.

2) 모델에서 웅변적인 관계를 정의합니다.

설명서를 읽어 보았지만 여전히 다음 내용에 대해 혼란스럽습니다.

  1. 둘 다 사용해야 하나요, 아니면 하나만 사용하면 되나요?

  2. 두 가지를 동시에 사용하는 것이 잘못된 것입니까?아니면 그것이 중복되게 하거나 갈등을 일으키나요?

  3. 마이그레이션 칼럼에서 외국인 키를 언급하지 않고 웅변 관계를 사용하면 어떤 이점이 있습니까?

  4. 뭐가 다른 거지?

이것들이 제가 지금 가지고 있는 코드입니다.마이그레이션 파일에 설정한 외부 키를 제거해야 하는지 여부는 아직 불분명합니다.

마이그레이션:

  public function up()
    {   

       Schema::create('apps', function (Blueprint $table) {
          $table->increments('id');
          $table->string('app_name');
          $table->string('app_alias');
          $table->timestamps();
          $table->engine = 'InnoDB';
       });

      // This is the second Migration table
      Schema::create('app_roles', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('app_id')->unsigned()->index();
          $table->integer('user_id')->unsigned()->index();
          $table->integer('role_id')->unsigned()->index();
          $table->engine = 'InnoDB';

          $table->unique(array('app_id', 'user_id'));

          $table->foreign('app_id')
                ->references('id')
                ->on('apps')
                ->onDelete('cascade');

          $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

          $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');
        });     
    }

유창한 관계를 가진 모델:

// App Model
class App extends Model
{

     public function appRoles() {
         return $this->hasMany('App\Models\AppRole');
     }
}

// AppRole Model
class AppRole extends Model
{
   public function app() {
       return $this->belongsTo('App\Models\App');
   }

   public function user() {
       return $this->belongsTo('App\User');
   }

   public function role() {
       return $this->belongsTo('App\Models\Role');
   }
}

// User Model
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    .....
    public function appRole() {
         return $this->belongsToMany('App\Models\AppRole');
     }
}

// Role Model
class Role extends EntrustRole
{
     public function appRole() {
         return $this->hasMany('App\Models\AppRole');
     }
}

누가 이것을 이해하는 것을 도와줄 수 있습니까?

둘 다 같이 갑니다.하나는 다른 하나 없이 완전하지 않습니다.관계가 제대로 작동하려면 이 두 가지를 모두 정의해야 합니다.

마이그레이션 파일에 외부 키를 정의한 경우 원시 쿼리를 작성할 경우에만 관계가 작동합니다.모델에서는 작동하지 않습니다. 모델에서 관계에 대해 아무것도 쓰지 않으셨기 때문입니다.

글을 쓰자마자hasMany당신의 모델들 중 하나의 모델에서, 그리고 다른 모델에서 대응하는 함수에서, 오직 당신의 모델들이 서로에 대해 알고 있을 때, 당신은 당신의 데이터베이스뿐만 아니라 당신의 모델을 통해서도 성공적으로 사물들을 질의할 수 있습니다.

또한 다음을 통해 적절하게 관계를 정의한 경우hasMany그리고.belongsTo당신의 모델에서, 그러나 모델의 표에 외국 키를 제공하지 않았습니다.belongsTo다른 테이블에서는, 당신의 관계가 통하지 않을 겁니다.

간단히 말해서, 둘 다 똑같이 의무적입니다.

Expellent는 모델명을 바탕으로 관계의 대외적인 키를 가정합니다.이 경우에는.App모델은 자동적으로 다음과 같이 가정됩니다.app_id따라서 마이그레이션할 때 다음을 지정할 필요가 없습니다.

$table->foreign('app_id')
->references('id')
->on('apps')
->onDelete('cascade');

문서화

언급URL : https://stackoverflow.com/questions/31339496/migration-foreign-key-vs-eloquent-relationships-in-laravel

반응형