Relation in custom pivot table returns empty collection
I have this structure:
class Place extends Model
{
public function discounts(): BelongsToMany
{
return $this->belongsToMany(Discount::class)->using(DiscountPlace::class);
}
}
class Discount extends Model
{
public function places(): BelongsToMany
{
return $this->belongsToMany(Place::class)->using(DiscountPlace::class);
}
}
class DiscountPlace extends Pivot
{
public $incrementing = true;
public function activities(): MorphMany
{
return $this->morphMany(Activity::class, 'subject', 'subject_type', 'subject_id');
}
}
Why does calling Place::first()->discounts->first()->pivot->activities return an empty collection, even though there is data?
If I call DiscountPlace::find(1)->activities, everything is fine.
There is no many-to-many relationship defined on the Discount model, so the pivot property is null - you need this relationship on Discount if you intend to use the Pivot model:
class Discount extends Model
{
public function places(): BelongsToMany
{
return $this->belongsToMany(Place::class)->using(DiscountPlace::class);
}
}
Thanks for the tip, but it didn't work because I didn't specify the id of my DiscountPlace model field:
class Discount extends Model
{
public function places(): BelongsToMany
{
return $this->belongsToMany(Place::class)->using(DiscountPlace::class)->withPivot('id');
}
}