I followed the instructions here to add a relationship to the User model.
Here is some code :
class AddRelationships
{
/**
* @param Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen(GetModelRelationship::class, [$this, 'getModelRelationship']);
$events->listen(GetApiRelationship::class, [$this, 'getApiAttributes']);
$events->listen(Serializing::class, [$this, 'prepareApiAttributes']);
$events->listen(WillGetData::class, [$this, 'includeChallenges']);
$events->listen(WillSerializeData::class, [$this, 'loadChallenges']);
}
/**
* @param GetModelRelationship $event
*/
public function getModelRelationship(GetModelRelationship $event)
{
if ($event->isRelationship(User::class, 'challenges')) {
return $event->model->belongsToMany(Challenge::class, 'gb_challenge_user');
}
}
/**
* @param GetApiRelationship $event
*/
public function getApiAttributes(GetApiRelationship $event)
{
if ($event->isRelationship(User::class, 'challenges')) {
return $event->serializer->belongsToMany($event->model, ChallengeSerializer::class);
}
}
/**
* @param Serializing $event
*/
public function prepareApiAttributes(Serializing $event)
{
if ($event->isSerializer(UserSerializer::class)) {
$event->attributes['challenges'] = $event->model->challenges;
}
}
/**
* @param WillGetData $event
*/
public function includeChallenges(WillGetData $event)
{
if (
$event->isController(ListUsersController::class)
|| $event->isController(ShowUserController::class)
) {
$event->addInclude('challenges');
}
}
public function loadChallenges(WillSerializeData $event)
{
if (
$event->isController(ListUsersController::class)
|| $event->isController(ShowUserController::class)
) {
$event->data->load('challenges');
}
}
}
I get the challenges attribute when calling the API from the browser, but the data from the challenges isn't serialized, looks like my getApiAttributes
method has no effect...
Did anyone have this problem yet ?