laravel-json-api / eloquent

Serialize Eloquent models to JSON API resources
MIT License
12 stars 15 forks source link

Relationship field filters #16

Closed devinfd closed 3 years ago

devinfd commented 3 years ago

This PR adds the following filters: Has, WhereHas, and WhereDoesntHave.

TLDR

Code taken from https://github.com/laravel-json-api/eloquent/pull/11. Made the requested changes. I'm not sure if tests are necessary as I don't see any other filter tests. After this PR is accepted, close https://github.com/laravel-json-api/eloquent/pull/11

Usage

use App\Model\Post;
use LaravelJsonApi\Eloquent\Filters\WhereHas;
use LaravelJsonApi\Eloquent\Fields\Relations\HasOne;

class PostSchema extends Schema
{
    /**
     * The model the schema corresponds to.
     *
     * @var string
     */
    public static string $model = Post::class;

    /**
     * Get the resource fields.
     *
     * @return array
     */
    public function fields(): array
    {
        return [
            ...
            HasOne::make('author'),
        ];
    }

    /**
     * Get the resource filters.
     *
     * @return array
     */
    public function filters(): array
    {
        return [
            ...
            WhereHas::make($this, 'author'),
        ];
    }
}
use App\Model\Authors;
use LaravelJsonApi\Eloquent\Filters\Where;

class AuthorSchema extends Schema
{

    /**
     * The model the schema corresponds to.
     *
     * @var string
     */
    public static string $model = Authors::class;

    /**
     * Get the resource fields.
     *
     * @return array
     */
    public function fields(): array
    {
        return [
            ...
        ];
    }

    /**
     * Get the resource filters.
     *
     * @return array
     */
    public function filters(): array
    {
        return [
            ...
            Where::make('status'),
        ];
    }
}
GET /api/v1/posts?filter[authors][status]=active
lindyhopchris commented 3 years ago

Thanks for submitting this. Just wanted to let you know that I'm going to do some open source work this weekend, so will review/merge this then.

devinfd commented 3 years ago

No problem, thank you for your work in this project. It's fantastic!

lindyhopchris commented 3 years ago

Thanks for submitting this. There's a few changes I'd like - but think it'll be quicker if I merge then make the changes myself.