It's a many-to-many relationship. [Attachment] can be used for user's avatar or comment detail attachment image. table structure:
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)
first, in AppServiceProvider, I had custom morphMap:
Relation::morphMap([
'comment_detail' => CommentDetail::class,
'user_avatar' => User::class,
]);
then in CommentDetail model, define attachment() method to get all attachments:
public function attachments()
{
return $this->morphToMany(
Attachment::class,
"target",
"attachment_relationships",
"target_id",
"attachment_key",
"cid",
"key"
);
}
now the problem comes. when I create a attachment through commentDetail like this:
$commentDetail = CommentDetail::findOrFail(4);
$attachment = $commentDetail->attachments()->create([
'key' => (string)\Uuid::uuid4(),
]);
it will create a [Attachment] record:
id key
10 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56
and a [AttachmentRelationship] record:
id target_type target_id attachment_key
1 comment_detail 7 10
my question: why the [AttachmentRelationship] record 'attachment_key' field's value is not the [Attachment] record 'key' field's value = 968e22b8-e4fb-4743-bf08-8ac9cd8ecd56 (now it's 'id' field's value = 10) ?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire