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

stephen_p's avatar

Need help with Eloquent data model/relationships or query statement

I'm trying to get all reservation times for all accounts belonging to the authenticated user. Here are the models:

users: id, name

account_user (pivot): account_id, user_id

accounts: id, accountname

account_schedule (pivot): account_id, schedule_id

schedules: id, accountname, reservationtime

Relationships:

  1. users has many accounts
  2. accounts has many schedules

I have tried both query builder and eloquent and can't figure it out. Do I need to fix the data model? If the data model is good, what would the eloquent statement be?

Any help would be greatly appreciated!!

0 likes
5 replies
stephen_p's avatar

When a user is authenticated, I want to pass the reservationtimes to the view for the accounts associated to the authenticated user.

InaniELHoussain's avatar

I see, I'll think for a while, honestly I'd think a way with Native SQL

goatshark's avatar

@stephen_p In my experience, pivot tables are not used for hasMany/belongsTo relationships. I think a hasManyThrough relationship between User and Schedule would get you most of the way there.

On User:

public function schedules()
{
    $this->hasManyThrough(Schedule::class, Account::class);
}

I'm not sure this will work with your table structure though. Unless there's a specific reason you're using pivot tables, you might try:

  1. Dumping the pivot tables
  2. Add a user_id (integer) column on acccounts
  3. Add an account_id (integer) column on schedules.

Then:

user-->hasMany-->account

user-->hasManyThrough-->schedule

account-->belongsTo-->user

account-->hasMany-->schedule

schedule-->belongsTo-->account

Then you could $user->schedules(). .....or something like that. :)

stephen_p's avatar

Thanks for the reply. I came across this yesterday in the Laravel documentation, but resisted because I didn't want to be locked into the account->belongsTo->User inverse relationship. Sorry, I should have put the inverse relationships in my original post.

The purpose for the pivot table is to leave the flexibility for many-to-many "accounts->has many->users" relationship.

I would lose this relationship for user #2 to infinity for any given account.

Is there a way to do the hasManyThrough a many-to-many relationship? Or something comparable?

Please or to participate in this conversation.