【问题标题】:Laravel Eloquent hasManyThrough relation + paginationLaravel Eloquent hasManyThrough 关系+分页
【发布时间】:2016-09-26 10:29:52
【问题描述】:

我有三张桌子:

Videos:
-id
-name
-another fields

Cats:
-id
-name
-another fields

Cats_videos:
-id
-cat_id
-video_id

还有三个 Eloquent 模型:

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';
}

所以,我想在一只猫中接收所有视频,然后对结果进行分页。我试图这样做:

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

我收到这样的 sql:

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

但我需要“cats_videos.video_id = videos.id”而不是“cats_videos.id = videos.id”。如何使用“hasManyThrough”来做到这一点?还是我应该看看别的?

【问题讨论】:

    标签: php mysql pagination eloquent has-many-through


    【解决方案1】:

    问题解决了。我只需要使用 belongsToMany。

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

    【讨论】:

      猜你喜欢
      • 2020-10-14
      • 2019-03-26
      • 2015-07-27
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2018-10-18
      相关资源
      最近更新 更多