这是一种多对多的关系。 [附件]可以用于用户的头像或评论细节附件图像。表结构:
CommentDetail
id - integer
cid - integer
content - text
User
id - integer
name - string
Attachment
id - integer
key - string
AttachmentRelationship
id - integer
target_type - string ('user_avatar' or 'comment_detail')
target_id - integer (User -> id or CommentDetail -> cid)
attachment_key - string (Attachment -> key)
首先,在AppServiceProvider中,我有自定义的morphMap:
Relation::morphMap([
'comment_detail' => CommentDetail::class,
'user_avatar' => User::class,
]);
然后在CommentDetail模型中,定义attachment()方法以获取所有附件:
public function attachments()
{
return $this->morphToMany(
Attachment::class,
"target",
"attachment_relationships",
"target_id",
"attachment_key",
"cid",
"key"
);
}
现在问题来了。当我通过commentDetail创建一个附件时:
$commentDetail = CommentDetail::findOrFail(4);
$attachment = $commentDetail->attachments()->create([
'key' => (string)\Uuid::uuid4(),
]);
它将创建一个[附件]记录:
id key
10 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56
和[AttachmentRelationship]记录:
id target_type target_id attachment_key
1 comment_detail 7 10
我的问题:为什么[AttachmentRelationship]记录' attachment_key'字段的值不是[附件]记录'键'字段的值= 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56(现在' id'字段的值= 10)?