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

Vinze's avatar
Level 3

Relationship on multiple keys

I'm having some question about managing my model relations. Currently I'm working on a project where the database is truncated and repopulated automatically every night. I can't change the structure of the tables but I need to setup some relations between them.

See the following example:

Table: cabinets (Cabinet)

  • debtor_number
  • cabinet_number
  • (other fields)

Table: cabinetchecks (CabinetCheck)

  • debtor_number
  • cabinet_number
  • (other fields)

Now I need to load all cabinets of a specific debtor, and eager load the check of those cabinets. So I though using this would be easiest:

<?php
class Cabinet extends Eloquent {

    public function check() {
        $this->hasOne('App\Models\CabinetCheck', 'debtor_number', 'debtor_number')->where('cabinet_number', $this->cabinet_number);
    }

}

$cabinets = Cabinet::with('check')->where(debtor_number, 1)->get();
?>

Unfortunately this doesnt work because '$this->cabinet_number' is still null. Now I managed to get it working using the following code:

<?php
$cabinets = Cabinet::where(debtor_number, 1)->get();
$cabinets->load('check');
?>

This solves my problem without any hacking, but is this the 'Laravel way' of doing stuff with composite keys ?

Edit: Just noticed my solution DOES NOT work.. $this->cabinet_number always returns the value of the first model, so when trying to eager load multiple rows it returns the same relation..

0 likes
3 replies
Vinze's avatar
Level 3

Nope, I solved it by getting all results and then filtering the collection. Laravel/Eloquent itself doesn't support composite keys unfortunately.

Please or to participate in this conversation.