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

rob's avatar
Level 2

One-to-Many + Many-to-Many; How to?

I've been puzzling this one, and not been able to get it to work for some reason. I want to do this:

tables

Where bookings are created and owned by one user. But multiple (other) users can choose to join a booking as a passenger.

I'd like to be able to do something like

$booking->user to access the user who created the booking.

$booking->passengers to access a collection of users that have joined the booking.

Hope that makes sense. How would you guys approach it? Thanks

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

You can call a relationship whatever you wish, it just requires that you are more explicit whenever defining the relationship:

// Booking.php


// Calling the relationship 'user' infers a 'user_id' foreign key
public function user()
{
    return $this->belongsTo(User::class);
}

// The same relationship could be called 'owner' if that makes more sense in the context of your domain, but you must be explicit about the foreign key
public function owner()
{
    return $this->belongsTo(User::class, 'user_id');
}


// Because the relationship is called passengers, you must be explicit about the pivot table name and foreign keys
public function passengers()
{
    return $this->belongsToMany(User::class, 'booking_user', 'booking_id', 'user_id');
}
mballaag's avatar

You can call a relationship everywhere, after well declare your model booking.php

// Booking.php


// the relation 'user' refers to your 'user.php' model
public function user()
{
    return $this->belongsTo('App\user');
}

// the relation passenger, reference user model first, table namein second and table foreign keys attribs for the last
public function passengers()
{
    return $this->belongsToMany('App\user, 'booking_user', 'booking_id', 'user_id');
}
rob's avatar
Level 2

Thanks guys, explicitly setting up the pivot works nicely.

Cheers!

Please or to participate in this conversation.