Ivan
Ivan

Reputation: 11

Laravel Eloquent hasManyThrough relation + pagination

I have three tables:

Videos:
-id
-name
-another fields

Cats:
-id
-name
-another fields

Cats_videos:
-id
-cat_id
-video_id

And three Eloquent models:

class cat extends Model
{
    protected $table = 'cat';

    public function AllCatVideos()
    {
        return $this->hasManyThrough('App\videos', 'App\cats_videos','cat_id','id');
    }
}

class videos extends Model
{
    public $timestamps = false;
    protected $table ='videos';
}

class cats_videos extends Model
{
    protected $table = 'cats_videos';
}

So, I want to receive all videos in one cat and then paginate the results. I trying to do like this:

$cat = new Cats();
    $videos = $cat->find(58)->AllCatVideos()->toSql();

And I receiving the sql like this:

select * from `videos` inner join `cats_videos` on `cats_videos`.`id` = `videos`.`id` where `cats_videos`.`cat_id` = 58

But I need "cats_videos.video_id = videos.id" instead of "cats_videos.id = videos.id". How can I do this using "hasManyThrough"? Or I should look something else?

Upvotes: 0

Views: 267

Answers (1)

Ivan
Ivan

Reputation: 11

Problem solved. I just need use belongsToMany.

class cat extends Model{
public function Videos()
{
    return $this->belongsToMany('App\videos','cats_videos','cat_id','video_id');
}}

Upvotes: 1

Related Questions