Laravel - Union + Paginate at the same time?

后端 未结 12 587
有刺的猬
有刺的猬 2020-12-09 04:20

Brief:

I am trying to union 2 tables recipes and posts then add ->paginate(5) to the queries.

But

12条回答
  •  青春惊慌失措
    2020-12-09 04:46

    The accepted answer works great for Query Builder.

    But here's my approach for Laravel Eloquent Builder.

    Assume that we're referring to same Model

    $q1 = Model::createByMe();       // some condition
    $q2 = Model::createByMyFriend(); // another condition
    
    $q2->union($q1);
    $querySql = $q2->toSql();
    
    $query = Model::from(DB::raw("($querySql) as a"))->select('a.*')->addBinding($q2->getBindings());
    
    $paginated_data = $query->paginate();
    

    I'm using Laravel 5.6

提交回复
热议问题