【问题标题】:Laravel Database Migrations Naming for $table->morphs()?Laravel 数据库迁移为 $table->morphs() 命名?
【发布时间】:2020-05-11 14:36:09
【问题描述】:

根据文档中类似标签的表名是:$table->morphs('taggable');

但是像 product_tags 这样的名称呢?

$table->morphs('producttagable');

$table->morphs('product_tagable');

$table->morphs('productTagable');

也是模态的:

  public function tagable()
  {
      return $this->morphTo();
  }

product_tags 的正确函数名称是什么?

【问题讨论】:

  • producttaggable 没有错。

标签: laravel laravel-migrations


【解决方案1】:

帮助器$table->morphs(...) 创建..._id..._type,如https://laravel.com/docs/6.x/migrations#creating-columns 中的文档所述:

添加 taggable_id UNSIGNED BIGINT 和 taggable_type VARCHAR 等效列。

所以你的参数'taggable' 只是前缀。我通常使用名称'morphable',这是一种更通用的列名定义方式。

然后您可以在您的关系中使用它,例如:

public function posts()
{
    return $this->morphToMany('App\Post', 'morphable');
}

这将在morphable_idmorphable_type 列上建立关系。

【讨论】:

  • 除非在一个数据库表中存在 2 个多态关系,否则您将需要另一个可定义的名称。
  • 是的,虽然我还没有遇到过这种情况,因为它听起来像一个神表(添加一个$casts = ['data' => 'array']作为一个data列,你基本上可以在一张表中管理你的整个数据库:p)
  • 这不是叫 WordPress 吗 :) 它很少见,但我已经用过几次了,你可以为任何多对多的需求创建多态多态多态多表 :)跨度>
猜你喜欢
  • 2018-12-07
  • 2015-11-25
  • 2018-04-04
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 2022-11-17
  • 1970-01-01
相关资源
最近更新 更多