我们目前正在 codotto.com 中开发一项功能,用户可以在其中对 IT 聚会发表评论。每个评论都可以有一个答案。我们只允许一级深层答案,例如:
- Comment 1 - Answer to comment 1 - Answer to comment 1 - Comment 2 - Answer to comment 2 - Answer to comment 2
我有以下数据库结构:
// meetup_messages - id - user_id - meetup_id - meetup_message_id (nullable) -> comments that do not answer will have this set to nullable
在我的模型中,我将 answers
定义为 HasMany
关系:
class MeetupMessage extends Model { // ... public function answers(): HasMany { return $this->hasMany(self::class, 'meetup_message_id'); } }
然后在我的控制器上,我收到所有没有答案的评论:
public function index( IndexMeetupMessageRequest $request, Meetup $meetup, MeetupMessageService $meetupMessageService ): MeetupMessageCollection { $meetupMessages = MeetupMessage::with([ 'user', // 'answers' => function ($query) { // $query->limit(3); // } 'answers' ]) ->whereNull('meetup_message_id') ->whereMeetupId($meetup->id) ->paginate(); return new MeetupMessageCollection($meetupMessages); }
然后在我的 MeetupMessageCollection
上:
class MeetupMessageCollection extends ResourceCollection { public function toArray($request) { return parent::toArray($request); } }
然后在我的 MeetupMessageResource
上:
<?php namespace AppHttpResources; use IlluminateHttpResourcesJsonJsonResource; use IlluminateSupportCollection; class MeetupMessageResource extends JsonResource { public function toArray($request) { return collect([ // 'answers' => new MeetupMessageCollection($this->whenLoaded('answers')), ]) ->when( is_null($this->meetup_message_id) && $this->relationLoaded('answers'), function (Collection $collection) { $collection->put('answers', MeetupMessageCollection::collection($this->answers)); } ); } }
但我收到以下错误:调用未定义的方法 App\Models\Meetup\MeetupMessage::mapInto()
。我如何通过将 answers
传递给它来仍然使用 MeetupMessageCollection
?
正如 @matialauriti 指出的,你不能在 Laravel 中的集合中使用资源集合
我的解决方案是将我的资源形成拉至私有方法,并在存在
answers
时重新使用它: