MySql -基于多对多数据透视表值的唯一键

时间:2021-07-19 22:21:15

I have to manage artists and albums tables.

我必须管理艺术家和专辑。

| artists      |  | albums       |  | album_artist |
+--------------+  +--------------+  +--------------+
| id           |  | id           |  | id           |
| artist       |  | album        |  | album_id     |
| created_at   |  | created_at   |  | artist_id    |
| updated_at   |  | updated_at   |  +--------------+
+--------------+  +--------------+

Keeping in mind that this is a many-to-many relation, I do need to find a way to get the album-artist(s) pair unique, since albums may have the same name yet belonging to different artists (f.e. "Greatest Hits" album of 2Pac and "Greatest Hits" of Notorious BIG). Is there a known way/pattern to address this problem?

记住,这是一个多对多的关系,我确实需要找到一种方法使专辑艺术家(s)对是唯一的,因为专辑可能有相同的名字但属于不同的艺术家(f.e)。2Pac专辑《最伟大的成功》和BIG专辑《最伟大的成功》)。有什么已知的方法/模式来解决这个问题吗?

Thank you.

谢谢你!

1 个解决方案

#1


3  

I have done it before, with creating a unique constraint on the album_id,artist_id.

我以前做过,在album_id (artist_id)上创建一个惟一的约束。

This will make it possible to have albums for different artists. As the artists id will differentiate. In your migration put.

这将使拥有不同艺术家的专辑成为可能。就像艺术家id一样。在你的迁移。

$table->unique(['album_id', 'artist_id']);

In traditional database design, this is called a composite key, which is two or more columns, which makes the table unique, in most pivot table this will be the two foreign keys.

在传统的数据库设计中,这被称为复合键,它是两个或多个列,这使得表是惟一的,在大多数pivot表中,这是两个外键。

#1


3  

I have done it before, with creating a unique constraint on the album_id,artist_id.

我以前做过,在album_id (artist_id)上创建一个惟一的约束。

This will make it possible to have albums for different artists. As the artists id will differentiate. In your migration put.

这将使拥有不同艺术家的专辑成为可能。就像艺术家id一样。在你的迁移。

$table->unique(['album_id', 'artist_id']);

In traditional database design, this is called a composite key, which is two or more columns, which makes the table unique, in most pivot table this will be the two foreign keys.

在传统的数据库设计中,这被称为复合键,它是两个或多个列,这使得表是惟一的,在大多数pivot表中,这是两个外键。