Reputation: 1005
I have the following 2 tables:
+-------+ +------------------------------+
| users | | blocked_users |
+-------+ +------------------------------+
| id | | id, user_id, blocked_user_id |
+-------+ +------------------------------+
My User
class has the following relationship defined:
/**
* Users the instance user has blocked.
*
* @ORM\OneToMany(
* targetEntity="BlockedUser",
* mappedBy="blocker",
* fetch="EXTRA_LAZY",
* cascade={"persist", "remove"},
* orphanRemoval=true
* )
*
* @var BlockedUser[]|Collection
*/
protected $blockedUsers;
I haven't defined a blockedByUsers
relationship, since a user should't know who blocked them. However, when I deleted a User who has been blocked I get a foreign key exception. I could fix the exception by adding another User::$blockedByUsers
relationship, but as I said I don't believe that should exist.
Is there any other way to create the cascading foreign key relationship?
Upvotes: 2
Views: 987
Reputation: 7127
You can set the foreign key on the blocked_users
table when you define the relationship from blocked_user_id
to user
:
@JoinColumn(name="blocked_user_id", referencedColumnName="id", onDelete="cascade")
The onDelete
option will cascade deletion as you expect.
Upvotes: 1