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

richtestani's avatar

hasManyThrough Confusion

I have a pretty typical database setup but having difficulties getting a relationship to work.

I have three tables: Users, Members and Clubs.

Clubs -> hasMany Members Member -> hasManyThrough User, Club User -> belongsToMany Member

The tables schema looks like:

users table:

$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('username')->unique();

members table

$table->increments('id');
$table->integer('club_id')->unsigned();
$table->foreign('club_id')->references('id')->on('clubs')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();

clubs table

$table->increments('id');
$table->string('name');
$table->text('description')->nullable();
$table->boolean('active')->default(true);
$table->timestamps();

From here, in my Club model, I define a function:

public function members()
{

return $this->hasManyThrough('App\Member', 'App\User', 'club_id', 'user_id');

 }

In my Member model, I define a user function:

public function user()
{
  return $this->hasMany('App\User');
}

I have a record of a club with an id of 1, a user record with a record of 1 and a member record with user_id=1 and club_id = 1.

In my ClubController, I make a call to the Club model:

  $club = Club::find(1);

  dd($club->members());

The above will show me the proper relationships:

  #throughParent: User {#250 ▶}
  #farParent: Club {#258 ▶}
  #firstKey: "club_id"
  #secondKey: "user_id"
  #localKey: "id"
  #query: Builder {#256 ▶}
  #parent: User {#250 ▶}
  #related: Member {#255 ▶}
  }

The Club model shows the correct club but no member or user data is present. I should have the 1 member for this club.

If I chain get() to the the members, it returns an SQL error where an unknown column of users.club_id is trying to be selected.

Finally if I try and access the user, $club->members()->user()->username,

I get a fatal error regarding a member function member() on boolean

What is wrong with my setup here? Thanks Rich

0 likes
0 replies

Please or to participate in this conversation.