Skip to content

Support polymorphic to-many relationships #8

Closed
@lindyhopchris

Description

@lindyhopchris

Given a posts resource has a has-many relationship called media, that may contain images, audios and videos . The JSON:API resource object may look like this.

{
  "type": "posts",
  "id": "5",
  "relationships": {
    "media": {
      "data": [
        { "type": "videos", "id": "7" },
        { "type": "audios", "id": "9" },
        { "type": "images", "id": "38" },
        { "type": "videos", "id": "11" },
        { "type": "images", "id": "234" },
      ]
    }
  }
}

The package doesn't actually support this at the moment. The reason being is that there is no Eloquent relation for this. In this scenario, the Post model would look like this:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    
    public function audios()
    {
        return $this->hasMany(Audio::class, 'media');
    }
    
    public function images()
    {
        return $this->hasMany(Image::class, 'media');
    }

    public function videos()
    {
        return $this->hasMany(Video::class, 'media');
    }
}

The relations might not just be hasMany. For example, if Image models could be attached to multiple Post models, the image relation could be a belongsToMany. Likewise, if Image models could be attached to multiple different types of models, it could be a morphedByMany relation.

Merging these all into a single JSON:API relation is not currently supported.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions