niksak
niksak

Reputation: 23

Laravel Eloquent relationship (3 tables)

I have 3 tables in a database
1.Volume:id,volume,number,...
2.Papers:id,volume_id,title,...
3.Editor_name:id,idP(Papers ID),name...
The 'Papers' table has column 'volume_id' coming from 'Volume' and 'Editor_name' has 'idP' column which connected to 'Papers' table column 'id'.

I don't know which method to use(hasMany or hasManyThrough) and how to define functions in the controller (VolumeController).
I have 3 model (Volume,Papers,Names)
Volume model :

  public function names()
{
    return $this->hasManyThrough(Names::class, Papers::class,'volume_id','idP','id','id',);
}

or:
Volume model :

public function papers()
{
    return $this->hasMany(Papers::class,'volume_id');
}

Papers model :

public function volume()
{
    return $this->belongsTo(Volume::class,'volume_id');
}
public function names()
{
    return $this->hasMany(EditorName::class,'idP');
}

Names model :

  public function papers()
{
    return $this->belongsTo(Papers::class,'idP');
}

And what I want:
URI /volume/1/1
Volume 1 Number 1
Title 1
Editor 1 Editor 2 Editor 3
Title 2
Editor 4 Editor 5
Title 3
Editor 6 Editor 7 Editor 8 ...
URI /volume/1/2
Volume 1 Number 2
Title 4
Editor 9 Editor 10 Editor 11
Title 5
Editor 12

VolumeController

 public function papers($id){
    $papers = Papers::all()->where('volume_id',$id);      
    return view('volume_ID',compact('papers'));

}

Upvotes: 0

Views: 1641

Answers (1)

STA
STA

Reputation: 34678

Volume Model :

public function names()
{
    return $this->hasManyThrough(Names::class, Papers::class,'volume_id','idP','id','id',);
}

public function papers()
{
    return $this->hasMany(Papers::class,'volume_id');
}

In controller :

$id = 1;
$q = Volume::with('names', 'papers')->findOrFail($id);

Blade :

Volume : {{ $q->volume }}
Number : {{ $q->number }}

@foreach($q->papers as $paper)
   Paper Title : {{ $paper->title }}
@endforeach

@foreach($q->names as $name)
   Name : {{ $name->name }}
@endforeach

Upvotes: 2

Related Questions