简体   繁体   中英

How should I replace a hasMany() relationship with Laravel API Resources for Lumen

I'm migrating a Laravel 5.7 app to Lumen, and introducing at the same time Laravel API Resources

In my old codebase, I had:

$tournaments = Auth::user()->tournaments();

With

public function tournaments()
{
    return $this->hasMany('App\Tournament');
}

But now, in Lumen, I use API Resources, so don't know how to get the same result, but with all the decorated extra fields that provide API resource.

I have:

class TournamentResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'user' => User::findOrFail(Auth::user()->id)->email,
            'championships' => ChampionshipResource::collection($this->whenLoaded('championships')),
            'competitors_count' => $this->competitors->count()
        ];
    }
}

Any Idea?

API Resources just format the way the data is returned. It doens't affect your relationships. The only thing you need to do is pass an object/collection (depending on the case) to the API Resource class.

Resource Collections

If you are returning a collection of resources or a paginated response, you may use the collection method when creating the resource instance in your route or controller:

 use App\\User; use App\\Http\\Resources\\User as UserResource; Route::get('/user', function () { return UserResource::collection(User::all()); }); 

As you can see, just use it:

TournamentsController.php

use App\Http\Resources\TournamentResource;

//

    public function index()
    {
        $tournaments = auth()->user()->tournaments;

        return TournamentResource::collection($tournaments);
    }

Check the documentation regarding this aspect. Also, to load the child items ( championship ), you can Eager Load / Lazy Eager Load the relationship items.


Observation:

In relationships, when you use it like a method ( auth()->user()->tournaments() ) you are accesing the relationship itself, usefull when you want to keep constraining the relation. When you use it as an attribute ( auth()->user->tournaments ) you are accesing the results of the query.

Check this answer for a better explanation.

If you migrating from Laravel to Lumen first thing you need to make sure that you have enable the eloquent in your app/bootstrap.php file.

Please follow this guide to make sure you are following the same. The above code should work once these are followed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM