Jenski
Jenski

Reputation: 1468

Relationships in Laravel Models

How can I write this without a join for a scope in a Laravel model as the 'id' field becomes ambiguous

 /**
  * Return events that social category name
  */
public function scopeWithSocialEvents($query)
{
    return $query->join('categories', 'events.event_type_id', '=', 'categories.id')
                ->where('categories.name', 'social');
}

Upvotes: 0

Views: 41

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use this:

public function eventType()
{
    return $this->belongsTo(Category::class);
}

public function scopeWithSocialEvents($query)
{
    return $query->whereHas('eventType', function($query) {
        $query->where('name', 'social');
    });
}

Upvotes: 1

Related Questions