小编Tho*_*pel的帖子

修改Ecto中的外键

我有这个已经运行并向上游发送的原始迁移:

create table(:videos) do
  add :url, :string
  add :title, :string
  add :description, :text
  add :user_id, references(:users, on_delete: :nothing)

  timestamps
end
create index(:videos, [:user_id])
Run Code Online (Sandbox Code Playgroud)

现在我希望将外键user_id改为级联删除,这样当用户被删除时,他的所有相关视频也将被删除.

我尝试过以下迁移:

alter table(:videos) do
  modify :user_id, references(:users, on_delete: :delete_all)
end
Run Code Online (Sandbox Code Playgroud)

但这会引发错误:

(Postgrex.Error) ERROR (duplicate_object): constraint "videos_user_id_fkey" for relation "videos" already exists
Run Code Online (Sandbox Code Playgroud)

如何根据我的要求制定将更改此外键的迁移脚本?


UPDATE

我最终得到了以下解决方案:

def up do
  execute "ALTER TABLE videos DROP CONSTRAINT videos_user_id_fkey"
  alter table(:videos) do
    modify :user_id, references(:users, on_delete: :delete_all)
  end
end

def down do
  execute "ALTER TABLE videos DROP CONSTRAINT videos_user_id_fkey" …
Run Code Online (Sandbox Code Playgroud)

elixir ecto phoenix-framework

30
推荐指数
4
解决办法
6090
查看次数

Postgres - 使用where子句缓慢简单连接

我在优化查询时遇到了一些麻烦,并且希望这里的某个人能够提供一些指示.

我有两张桌子:

CREATE TABLE "blog_cached_posts" (
    "id" int4 NOT NULL DEFAULT nextval('blog_cached_posts_id_seq'::regclass),
    "title" varchar(255),
    "content" text,
    "content_encoded" text,
    "published_at" timestamp(6) NULL,
    "written_by" varchar(255),
    "link" varchar(255),
    "blog_id" int4,
    "guid" varchar(255),
    "created_at" timestamp(6) NULL,
    "updated_at" timestamp(6) NULL,
    "is_highlighted_post" bool DEFAULT false
)
Run Code Online (Sandbox Code Playgroud)

使用blog_cached_posts.blog_id上的索引

CREATE TABLE "blogs" (
    "id" int4 NOT NULL DEFAULT nextval('blogs_id_seq'::regclass),
    "site_id" int4,
    "image_id" int4,
    "name" varchar(255),
    "description" text,
    "url" varchar(255),
    "rss_feed_url" varchar(255),
    "active" bool DEFAULT true,
    "created_at" timestamp(6) NULL,
    "updated_at" timestamp(6) NULL,
    "date_highlighted" date,
    "highlighted_category_feed_url" varchar(255),
    "position" int4
) …
Run Code Online (Sandbox Code Playgroud)

sql postgresql optimization performance join

4
推荐指数
2
解决办法
7350
查看次数