【问题标题】:Laravel 5.3, MySQL, proper foreign key setup in migrations (one to many, many to many)Laravel 5.3,MySQL,迁移中正确的外键设置(一对多,多对多)
【发布时间】:2017-11-04 19:02:44
【问题描述】:

设置外键限制的正确方法是什么?

假设我有模型PostUserTag

目前我的迁移都设置为:

对于Comment 型号:

$table->integer('posts_id')->unsigned(); //comment must belong to a post
$table->integer('user_id')->nullable()->unsigned(); //comment can belong to an user
$table->integer('something_id')->unsigned(); // each Something model will have at most 5 to 10 comments in it - this is what is called cardinality if I got it right so the average cardinality is 7.5

假设对于多对多关系,我在 PostsTags 之间有一个数据透视表:

$table->integer('post_id')->unsigned(); //connecting the post
$table->integer('tag_id')->unsigned(); //connecting the tag

现在我需要对字段进行索引,以便在执行我的数据库查询时尽可能快地执行它们。

我现在要做的是创建新的迁移:

$table->foreign('posts_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users'); 
$table->foreign('something_id')->references('id')->on('somethings');

数据透视表也是如此:

$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('tag_id')->references('id')->on('tags');

我的问题是:

  • 这是正确的方法吗?如果不是,我应该怎么做?
  • 这里是否有一些限制、缺点或任何我应该注意的事项?
  • 由于这里的基数约为 7.5,我会通过执行 $table->foreign('something_id')->references('id')->on('somethings'); 获得什么吗? comments.something_id 的更新永远不会在我的应用程序中发生,并且“创建新的 something 行”与“从 comment 行读取相关的 something 行”的比率非常低 1:10^5(粗略估计并在下一行优化中,我将致力于缓存查询,因此不确定这些信息的相关性)

【问题讨论】:

    标签: mysql laravel-5.3 laravel-migrations


    【解决方案1】:

    您不需要创建新的迁移文件来定义外键。

    $table->foreign('posts_id')->references('id')->on('posts');
    $table->foreign('user_id')->references('id')->on('users'); 
    $table->foreign('something_id')->references('id')->on('somethings');
    

    将那些放在注释表迁移文件中。和

    $table->foreign('post_id')->references('id')->on('posts');
    $table->foreign('tag_id')->references('id')->on('tags');
    

    在数据透视表迁移文件中。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2017-04-12
      • 2021-12-27
      • 2018-02-09
      • 2016-03-30
      • 2015-06-22
      • 2017-10-16
      • 2012-02-05
      • 2020-02-10
      相关资源
      最近更新 更多