Martijn
Martijn

Reputation: 529

Laravel 5.5 belongsTo not working as expected

I have three models with a relation, ReservedTicket extends Ticket:

App/TicketType:

class TicketType extends Model
{
    protected $fillable = [
        'name', 'startdate', 'enddate', 'countinuous', 'price', 'description', 'personal', 'total', 'minage', 'maxage', 'event_id', 'header_image_path', 'footer_image_path',
    ];

    public function event()
    {
        return $this->belongsTo(Event::class);
    }

    public function tickets()
    {
        return $this->hasMany(Ticket::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

App/Ticket:

class Ticket extends Model
{
    protected $fillable = [
        'user_id', 'first_name', 'last_name', 'prefix_name', 'ticket_type_id', 'sold_on', 'sold_by', 'scanned_at', 'scanned_by',
    ];

    public function ticketType()
    {
        return $this->belongsTo(TicketType::class, 'ticket_type_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

App/ReservedTicket:

class ReservedTicket extends Ticket
{
    protected $table = 'reserved_tickets';
}

I have set up the relations like I did on any other model in my application. I even tried specifying the foreign key column, but it's not happening.

I do get all Tickets if I use go through the hasMany() of TicketType. But the other way around it doesn't work.

Am I missing something because of the inheritance? I'm using an instance of ReservedTicket.

Upvotes: 0

Views: 732

Answers (1)

happymacarts
happymacarts

Reputation: 2604

When Extending a class to a new model you will need to define the relations in the extended class as well

class ReservedTicket extends Ticket
{
    protected $table = 'reserved_tickets';

    public function ticketType()
    {
        return $this->belongsTo(TicketType::class, 'ticket_type_id');
    }

    public function user()
    {
         return $this->belongsTo(User::class);
    }
}

Upvotes: 2

Related Questions