当前位置: 动力学知识库 > 问答 > 编程问答 >

php - 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?

网友答案:

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');
}}
分享给朋友:
您可能感兴趣的文章:
随机阅读: