cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
778 stars 109 forks source link

Use User morph (student, teacher) #603

Closed acrespo123 closed 3 years ago

acrespo123 commented 3 years ago

I have user morph to define profile of students and teachers, when I use the route of users the teacher and user info return null.

how I do to return the perfil info

lindyhopchris commented 3 years ago

Hi. Sorry, but you haven't provided enough information for me to know what the answer is. Please can you provide some code, probably the relevant Schema classes would be a good place to start.

acrespo123 commented 3 years ago

Sorry,

Model User:

public function userable() {
    return $this->morphTo();
}

Models teacher & student:

public function user() {
    return $this->morphOne('App\Models\User', 'userable');
}

User Schema:

public function getIncludePaths() {
    return ['student', 'teacher'];
}
public function getRelationships($resource, $isPrimary, array $includeRelationships) {
    return [
        'student' => [
            self::SHOW_DATA => isset($includeRelationships['student']),
            self::DATA => function () use ($resource) {
                return $resource->student;
            },
        ],
        'teacher' => [
            self::SHOW_DATA => isset($includeRelationships['teacher']),
            self::DATA => function () use ($resource) {
                return $resource->teacher;
            },
        ]
    ];
}

User & Teacher Schema:

public function getIncludePaths() {
    return ['user'];
}
public function getRelationships($resource, $isPrimary, array $includeRelationships) {
    return [
        'user' => [
            self::SHOW_DATA => isset($includeRelationships['user']),
            self::DATA => function () use ($resource) {
                return $resource->user;
            },
        ],
    ];
}

User Adapter:

protected function userable() {
    return $this->belongsTo();
}

Teacher $ Student Adapter:

public function user() {
    return $this->hasOne('userable');
}

With the routes for Teachers & Students return User the data;

$api->resource('teachers');
$api->resource('students');

But in Users route:

"relationships": {
    "student": {
        "data": null
    },
    "teacher": {
        "data": null
    }
},
lindyhopchris commented 3 years ago

The relationship on your User model is called "userable".

So doing $user->userable will return the student/teacher. Doing $user->teacher returns nothing because your user model doesn't have a teacher relationship.

So I don't understand why your user schema has both student and teacher relationships on it? When the model doesn't have student and teacher relationships?

acrespo123 commented 3 years ago

Thanks a lot. The morph relation is not explained on the guide