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

vandyczech's avatar

Eloquent relationship problem

I have three tables:

devices
departments
department_devices

I need create relationships between them like this:

device hasOne department
department belongsToMany devices

Is it one-to-many relationship?

So next I created the table department_devices with department_id and device_id referencing on id in devices and id in departments and these models:

Device
Department
DepartmentDevice

But i dont know how to put the relationships into the models ....

// Device
public function department(){
return $this->hasOne('App\Department');
}
// Department
public function devices(){
return $this->belongsToMany('App\Device');
}
0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you only need a pivot table on many to many relationships

device has one department so it should have a department_id column. Department table has nothing about the relationship.

in Device model, department() method return $this->belongsTo(Department::class);

in Department model, devices() method return $this->hasMany(Device::class);

vandyczech's avatar
$devices = Device::with('department')->get();

@foreach($devices as $device)

<tr>
<td>{{ $device->ip }}</td>
<td>{{ $device->department->name }}</td>
</tr>

@endforeach 

This working fine, but i have another tables location and types...

@foreach($devices as $device)

<tr>
<td>{{ $device->ip }}</td>
<td>{{ $device->department->name }}</td>
<td>{{ $device->location->name }}</td>
<td>{{ $device->types->name }}</td>
</tr>

@endforeach 

but what I have to use types and location with access data ... when the tables names locations, types I assume the table locations name location but locations name location, types name type ... I dont understand well

mwm's avatar

Maybe you need to define those relations as well

device belongsTo location
device belongsTo type
...

Please or to participate in this conversation.