Laravel 中的迁移外键与 Eloquent 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31339496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:55:14  来源:igfitidea点击:

Migration Foreign Key Vs Eloquent Relationships in Laravel

phpmysqllaraveleloquentlaravel-5

提问by Neel

In Laravel 5.1 I can see that table column relationships can be set-up in 2 ways:

在 Laravel 5.1 中,我可以看到可以通过两种方式设置表列关系:

1) Defining Foreign Keys in the Migration table.

1) 在迁移表中定义外键。

2) Defining the Eloquent relationships in the Models.

2) 定义模型中的 Eloquent 关系。

I have read the documentations and I am still confused on the following:

我已经阅读了文档,但我仍然对以下内容感到困惑:

  1. Do I need to use both or only 1 is needed?

  2. Is it wrong to use both at the same time? Or does it make it redundant or cause conflicts?

  3. What is the benefit of using Eloquent relationships without mentioning the Foreign keys in migration column?

  4. What is the difference?

  1. 我需要同时使用两者还是只需要 1 个?

  2. 同时使用两者有错吗?或者它是否使它变得多余或引起冲突?

  3. 使用 Eloquent 关系而不提及迁移列中的外键有什么好处?

  4. 有什么不同?

These are the codes I have now. Its still unclear to me if I need to remove the foreign keys I have set-up in my migration file.

这些是我现在拥有的代码。我仍然不清楚是否需要删除我在迁移文件中设置的外键。

Migration:

移民:

  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');
        });     
    }

Model with Eloquent Relationships:

具有雄辩关系的模型:

// 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');
     }
}

Can someone help me understand this please?

有人可以帮我理解这一点吗?

回答by Arslan Ali

Both go hand in hand. One is in-complete without the other one. If you want your relations to work properly, you need to define both of these things.

两者齐头并进。一个是不完整的,没有另一个。如果你想让你的关系正常工作,你需要定义这两件事。

If you have just defined the foreign key in a migration file, the relation would work just in case you write a raw query. It won't work on your models since, you haven't written anything about relations in your models.

如果您刚刚在迁移文件中定义了外键,则该关系将在您编写原始查询时起作用。它不适用于您的模型,因为您没有在模型中编写任何关于关系的内容。

So, as soon as you write hasManyin one of your models, and corresponding function in the other model, only then your models know about each other, and then you can successfully query things through your model as well as in your database.

所以,只要你hasMany在你的一个模型中编写了相应的函数,在另一个模型中编写了相应的函数,只有这样你的模型才会相互了解,然后你才能成功地通过你的模型以及你的数据库查询事物。

Also note that if you have properly defined relations through hasManyand belongsToin your models, but haven't provided foreign key in the table of the model who belongsToother table, your relations won't work.

另请注意,如果您在模型中hasManybelongsTo模型中正确定义了关系,但没有在模型表中提供外键 whobelongsTo其他表,则您的关系将不起作用。

In short, both are equally compulsory.

简而言之,两者同样是强制性的。

回答by apex39

Eloquent assumes the foreign key of the relationship based on the model name. In this case, the Appmodel is automatically assumed to have an app_idforeign key, so in your migrations you do not need to specify:

Eloquent 根据模型名称假定关系的外键。在这种情况下,App模型被自动假定为具有app_id外键,因此在您的迁移中您不需要指定:

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

Documentation

文档