Hello, I'm new to Laravel and I watched some videos about eloquent relationships but am still confused about the relationship with more than 3 tables. Please help me
-
in my case I tried to build it system with store movement for every item and make maintenance for items with 3 store movement (issued, received, returned) and every movement related to the department with the employee, and item at this point everything is done.
-
in case this item needs maintenance
- I made 4 table
-
maintenances table with these columns
- id
- item_id
- store_id
- status_after_maintenance
- maintenance_date
-
repairs table with these columns
- id
- repair_name like (hardware and software)
-
tools table with these columns
- id
- repair_id ex: (1) refer to hardware
- tool_name ex: (hard disk)
-
maintenance_repair_tool table as a pivot with these columns
/*Maintenance Model*/
class Maintenance extends Model
{
public function repairs()
{
return $this->belongsToMany(Repair::class, 'maintenance_repair_tool','maintenance_id','repair_id','id','id');
}
public function tools()
{
return $this->belongsToMany(Tool::class, 'maintenance_repair_tool','maintenance_id','tool_id','id','id');
}
}
/*Repair Model*/
class Repair extends Model
{
public function all_tools()
{
return $this->hasMany(Tool::class, 'repair_id', 'id');
}
public function maintenances()
{
return $this->belongsToMany(Maintenance::class, 'maintenance_repair_tool','repair_id','maintenance_id','id','id');
}
public function tools()
{
return $this->belongsToMany(Tool::class, 'maintenance_repair_tool','repair_id','tool_id','id','id');
}
}
/*Tool Model*/
class Tool extends Model
{
public function repair(){
return $this->hasOne(Repair::class,'id','repair_id');
}
public function maintenances()
{
return $this->belongsToMany(Maintenance::class, 'maintenance_repair_tool','tool_id','maintenance_id','id','id');
}
public function repairs(){
return $this->belongsToMany(Repair::class, 'maintenance_repair_tool','tool_id','repair_id','id','id');
}
}