maximos's avatar

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.

0 likes
4 replies
tykus's avatar

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);
    }
}
maximos's avatar

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');
    }
}
maximos's avatar

By the way, is there any way I can load activities for my DiscountPlace model? Something like this: Place::with('discounts.pivot.activities')->first()

Please or to participate in this conversation.