تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Cascade delete constraints0:00

There's one important thing we didn't cover in the last episode—uniqueness. So yes, we do have some constraints in place for our linking table. This means, for example, let's do this one here. The Post with an ID of 3 has a Tag with an ID of 1. However, if I delete the Post with an ID of 3, that should cascade and delete any records in the linking table as well. And the same is true in reverse. So the Post with an ID of 1 has a Tag with an ID of 1. But what if I were to delete that Tag? Well, because I have the same constraint in place, if I switch back, that too will cascade.

But what if I were to delete that tag? Well, because I have the same constraint in place, if I switch back, that too will cascade and delete the associated record in the linking table. So that alone is incredibly useful for maintaining integrity in our database, and again we allowed for that here. However, what if I duplicate a row? For example, the Post with an ID of 5 has a Tag with an ID of 3, even though I've already done it. Aha! So notice here, we have duplication that we do not want.

Identifying duplicate links0:59

Aha! So notice here, we have duplication that we do not want. There's no need to repeat this two times, and in fact, I can do it as many times as I want. And often, this will happen in situations where, for example, a User clicks a submit button really, really fast, multiple times. Now if you don't have any logic in place that basically disregards any repeated clicks, well, you can end up in a situation just like this. So it sounds like we need a new rule here. A rule that says the combination of the post ID and the tag ID must be unique, much like

Composite uniqueness rule1:26

So it sounds like we need a new rule here. A rule that says the combination of the post ID and the tag ID must be unique, much like a composite key. All right, let's go back to Sublime, and I'm going to keep my primary key. It's not overly necessary, and in fact, many people would never add a primary key to a linking table like this, but from my experiences, often these tables grow in something else where you will want a primary key, if only for your ORM. So personally, I usually keep them in there. But yeah, here and here. The combination of those two fields should be unique.

Adding unique index1:58

But yeah, here and here. The combination of those two fields should be unique. Here's how we do it. Table, unique, and I'll provide an array here. post_id and tag_id. Those two together must be unique. All right, let's do a php artisan migrate:fresh from scratch. And if I switch back here, very quickly, I will return our tags by running that query again. And then also, I will add a post.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟