【问题标题】:Laravel pagination with specific foreign key具有特定外键的 Laravel 分页
【发布时间】:2020-06-16 17:07:50
【问题描述】:

我需要在 Laravel 中进行分页,当我阅读 laravel 文档时,这里有几种方法可以做到这一点。但在我的情况下,它有点复杂。所以假设我的数据库中有两个表,table1table2(多对多关系),我想用特定的 ID 对table1 进行分页。所以我的意思是如果table1 包含 ids 1,2,3,4,5 ... n,我只想对 id 为 2 和 3 的行进行分页

我试过了:

private function check_wear($type){
        $products_id = array(); //here is ids which $type is set as 'ON'
        $wears = DB::select("SELECT prod_id FROM wears WHERE ".$type." = 'on' "); //Select specific products ids. (in our case it is **table1**)
        foreach ($wears as $wr){
            array_push($products_id,$wr->prod_id);
        }
        return $products_id; //return array with ids which should be paginate
    }
    public function hat($locale){

        $hat_prod_ids = $this->check_wear('coat');

        $p=12;
        $products = DB::table('products')->paginate($p); // 12 per page


        dd($products);

我的代码只对一个包含所有数据的表进行分页,是否有任何内置函数可以以某种方式编写逻辑条件?用于分页

【问题讨论】:

  • 在您分页的行中,您只需查询整个表。你永远不会使用$hat_prod_ids。您对$full_items 有什么期望?也许还要重新考虑您的数据库设计:您使用“ON”,为什么不使用布尔值(选择其中 type = coat 和 enabled = true)
  • 我的问题正是如此,如何使用$hat_prod_ids 过滤我的分页。
  • DB::table('products')->whereIn('id', $hat_prod_ids)->paginate($p); 在查询生成器上检查 whereIn 函数。

标签: php sql laravel


【解决方案1】:

如果您需要使用$hat_prod_ids 中的元素过滤分页,您可以使用WhereIn() 方法,该方法检查您的元素(在我们的例子中为id)是否存在于您的$hat_prod_ids并返回truefalse

$products = DB::table('products')
            ->whereIn('id',$hat_prod_ids)
            ->paginate($p);

添加该代码,现在您将能够仅对数组中匹配的 id 进行分页

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-04
    • 2022-01-13
    • 2022-01-27
    • 2021-07-27
    • 2015-11-04
    • 2010-12-14
    • 1970-01-01
    • 2010-10-22
    相关资源
    最近更新 更多