Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

richard_'s avatar

HasManyThrough relationship not working

I have three models with the following setup:

  • Bookings: id, [more fields]
  • Slots: id, [more fields]
  • Tickets: id, booking_id, slot_id

So in writing: A booking has one or more tickets associated with it. I now want to retrieve the Slots associated with a booking. So I wanted to leverage a hasManyThrough relationship:

// App\Models\Slot.php
...
public function booking()
{
    return $this->hasManyThrough(
            'App\Models\Booking',
            'App\Models\Ticket'
    }
}
...

// App\Models\Ticket.php
...
public function slot()
{
    return $this->hasOne('App\Models\Slot');
}
public function booking()
{
    return $this->hasOne('App\Models\Booking');
}
...

But somehow this results in a non-unique error:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'bookings' (SQL: select `bookings`.*, `bookings`.`slot_id` as `laravel_through_key` from `bookings` inner join `bookings` on 
`bookings`.`id` = `bookings`.`ticket_id` where `bookings`.`slot_id` in (3))

What am I missing here? Am I correct to use a hasManyThrough relationship? It looks like I'm messing up the default keys?

0 likes
3 replies
bobbybouwmann's avatar
Level 88

You're not looking at a one-to-many relationship, but to a many-to-many relationship. You can't use hasManyThrough with a many-to-many relationship.

If you want to slots from a booking you can do this

$booking = Booking::with('slots')->first();

Your relationship should look like this

// Booking.php
public function slots()
{
    return $this->belongsToMany('App\Models\Slot');
}

// Slot.php
public function bookings()
{
    return $this->belongsToMany('App\Models\Booking');
}
richard_'s avatar

Thanks! Stupid I didn't see this.... The tickets table is 'just' the pivot table of the many-to-many relationship.

The pivot table is also used for a model, but that's unrelated :) But that was what it made complex (at least to me ;) thinking i needed the ticket-model to connect the two outer models.

But as 1 booking can have more then 1 tickets; the result of the relation in slot.bookings can have doubles in the array. But a simple distinct on the relation fixes that.

In the end,this would be the relation on Slot.php:

public function bookings()
{
    return $this->belongsToMany('App\Models\Booking', 'tickets')
        ->distinct('id');
}

Please or to participate in this conversation.