gpt4 book ai didi

php - Insert Collection to saveMany Eloquent

转载 作者:行者123 更新时间:2023-12-01 22:30:08 25 4
gpt4 key购买 nike

我有一个充满模型的集合,我如何将它们放入关系的 saveMany 方法中?我知道它一定是一个数组,但是当我执行 $collection->toArray() 时,它们不再是 Eloquent 模型了。

public function uploadAndGetModels($messageId, array $attachments)
{
$models = new Collection();
$attachments = new Collection($attachments);
$attachments->each(function (UploadedFile $attachment) use ($messageId, $models) {
$identifier = $this->uploader->makeIdentifier($attachment->getClientOriginalExtension());
$this->uploader->uploadImage($attachment, "attachments/{$identifier}");
$model = new Attachment(array('message_id' => $messageId, 'path' => $identifier));
$models->push($model);
});

return $models;
}

$models 的结果是一个包含Attachment 模型的Collection

if ($request->hasFile('attachments')) {
$attachments = $attachmentRepository->uploadAndGetModels($message->id, $request->file('attachments'));
$message->attachments()->saveMany($attachments);
}

我该如何解决这个问题?

最佳答案

Collection 类有一个 all() 方法,它以模型数组的形式返回集合中的所有项目。

考虑到这一点,这应该可行...

$message->attachments()->saveMany($attachments->all());

关于php - Insert Collection to saveMany Eloquent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com