Reputation:
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,
];
}
}
Upvotes: 0
Views: 467
Reputation: 1433
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
).
Upvotes: 1