Reputation: 138
I am having trouble getting a query from HasManyThrough relation in Eloquent.
These are my tables
PAGES
SLIDESHOWS
SLIDES
My Page model:
class Page extends Model
{
public function slideshow_id(){
return $this->belongsTo(Slideshow::class);
}
public function slides(){
return $this->hasManyThrough('App\Slide','App\Slideshow','id','slideshow_id','slideshow_fk');
}
}
Controller
$page=Page::where("slug","=",$slug)->with('slides')->first();
Query log: I am not Page ID:3 with slideshow_fk:1, [? = 1]
select `slides`.*, `slideshows`.`id` from `slides` inner join `slideshows` on `slideshows`.`id` = `slides`.`slideshow_id` where `slideshows`.`id` in (?)
page->slides array:
[]
PhpMyAdmin SQL copy/paste:
Which are the correct 3 slides I need for my page.
Why do I get an empty array?
Upvotes: 3
Views: 1520
Reputation: 3704
You cannot you hasManyThrough() here as your implementation doesn't support the need for one.
Say you have three models A
, B
and C
and A
want to connect to C
via B
.
Then if you want to use hasManyThrough()
B
needs to have A
's primary key
as a foreign key
C
needs to have B
's primary key
as a foreign key
That is A <- B <- C
If I put this to your example, what you have is
A
have B
's primary key
as a foreign key
C
have B
's primary key
as a foreign key
Which is A -> B <- C
.
What you can do here is define models like this.
class Pages extends Model
{
public function slideshow()
{
return $this->belongsTo(Slideshow::class);
}
}
class Slideshow extends Model
{
public function slides()
{
return $this->hasMany(Slides::class);
}
}
class Slides extends Model
{
}
And query like
$pags = Pages::with('slideshow.slides')->where('slug', $slug)->first();
I suggest using proper naming conventions.
Upvotes: 4