attachment (Attachment) can be used as either a picture of the comment details (CommentDetail) or an avatar of the user"s (User). Their data structures are as follows:
CommentDetail
id - integer
cid - integer
content - text
User
id - integer
name - string
Attachment
id - integer
key - string
AttachmentRelationship
id - integer
target_type - string ("comment_detail" or "user_avatar")
target_id - integer (User -> id or CommentDetail -> cid)
attachment_key - string
first of all, I defined morphMap: in AppServiceProvider
Relation::morphMap([
"comment_detail" => CommentDetail::class,
"user_avatar" => User::class,
]);
then, in the CommentDetail model, define the method to get all attachments:
public function attachments()
{
return $this->morphToMany(
Attachment::class,
"target",
"attachment_relationships",
"target_id",
"attachment_key",
"cid",
"key"
);
}
finally, add attachments and associated data to a commentDetail:
$commentDetail = CommentDetail::findOrFail(4);
$attachment = $commentDetail->attachments()->create([
"key" => (string)\Uuid::uuid4(),
]);
the record created in the table corresponding to Attachment is:
< table > < thead > < tr > < th > id < / th > < th > key < / th > < / tr > < / thead > < tbody > < tr > < td > 10 < / td > < td > 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56 < / td > < / tr > < / tbody > < / table >the record in the AttachmentRelationship corresponding table is:
< table > < thead > < tr > < th > id < / th > < th > target_type < / th > < th > target_id < / th > < th > attachment_key < / th > < / tr > < / thead > < tbody > < tr > < td > 1 < / td > < td > comment_detail < / td > < td > 7 < / td > < td > 10 < / td > < / tr > < / tbody > < / table >my question is: why is the value of the attachment_key field of this record in AttachmentRelationship not the value of the key field in Attachment 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56 but the value of its id field 10? Is the association defined incorrectly? how to define it?
The 7 ofPS: target_id corresponds to the value of the cid field in the commentDetail record with an id of 4 is correct.