简体   繁体   中英

Laravel belongsToMany only returning one record?

I have 3 tables, I'll try to describe the schema.

scraper_profiles
    id
    name

scraper_collections
    id
    name

scraper_collection_entries
    profile_id
    collection_id

I am trying to return the items that belong to a collection,

class ScraperCollection extends Model
{
    public function items()
    {
        return $this->belongsToMany(ScraperProfile::class, 'scraper_collection_entries', 'profile_id', 'collection_id');
    }
}

Although it only returns one record in my resource?

class CollectionResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'creator' => new UserResource($this->creator),
            'items' => ScraperProfileResource::collection($this->items),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

Your Many to Many definition of foreign keys is reversed.

it should be:

 return $this->belongsToMany(
        ScraperProfile::class,
       'scraper_collection_entries',
       'collection_id',
       'profile_id');

A little thing to remember in Many to many relationship's definition:

if the first parameter is class A then the last parameter of the definition should be the foreign key of A ( A_id ).

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