简体   繁体   中英

Laravel Eloquent HasManyThrough returning empty array

I am having trouble getting a query from HasManyThrough relation in Eloquent.

These are my tables

PAGES

  • id
  • columns
  • slideshow_fk

SLIDESHOWS

  • id
  • columns

SLIDES

  • id
  • columns
  • slideshow_id

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:

http://prntscr.com/e0hy4e

Which are the correct 3 slides I need for my page.

Why do I get an empty array ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM