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

GotExx's avatar

belongsTo With pivot

Good morning, I would like to retrieve data from an intermediary table on an belongsTo relationship. Here is an extract from my database schema. db shema

  • An organization has many members via the table organization_user
  • Users has many Organization via the table organization_user
  • A user has only one position in an organisation. So only one row in the organization_user table per user/organization pair
  • A contract has a representative via its representative_id field.

Currently I get the User object via an belongsTo relationship like this:

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

however I want to retrieve the contract representative through the organization_user table to retrieve the value of the "position" field. How do I do this?

How do I do this?

0 likes
5 replies
GotExx's avatar

Hi @mareco & @tray2

Thank you for your answers. To be more precise:

  • A user can have several organisations
  • A contract has only one representative (that's why I use an belongsTo relationship and not an belongsToMany relationship)

Currently the relationship does not use the organization_user table, that's why the "position" field is not accessed.

achatzi's avatar

@gotexx Since the user can belong to many organizations it is possible to have many positions.

So you have 2 options

1 - Display all the possible positions of the representative

$contract = Contract::with('representative.organizations')->find($contract_id);

foreach ($contact->representative->organizations as $organization) {
    echo "{$organization->title} -> {$organization->pivot->position}";
}

2 - Have a relation between organization and contract (this is more tricky). Add a foreign key to contracts table referencing organizations and use something like this

$contract = Contract::find($contract_id);
$contract->load('representative.organizations' => fn($query) => $query->where('organizations.id', $contract->organization_id));

echo $contract->representantive->organizations->first()->pivot->position;

$contracts = Contract::with('representative.organizations')->get();

foreach ($contacts as $contract) {
	$representative_organization = $contact->representative->organizations->firstWhere('id', $contract->organization_id);
    echo "{$contract->uuid} -> {$contact->representative->name} -> {$representative_organization->title} -> {$representative_organization->pivot->position}";
}
GotExx's avatar

Apparently my first post was not clear enough, so I changed the diagram and updated the text.

There is indeed a relationship between contracts and organisations.

Please or to participate in this conversation.