【问题标题】:Fetching Multiple rows with multiple ID's using Eloquent使用 Eloquent 获取具有多个 ID 的多行
【发布时间】:2017-07-12 17:53:24
【问题描述】:

我有一个查询,它获取一个表,然后该查询的结果通过另一个查询传递。

然后我想从该查询中返回每一行中该列的所有值。

这会获取具有特定品牌 ID 的所有产品 ID

        // Fetch the Product List 
        $brandID = 1;
        $prodList = Products::whereBrandId($brandID);

        // Fetch the catalog ID of the Product
        $fetchID = $prodList->lists('id');

然后 print_r($fetchID) 返回数组。

Array ( [0] => 10011 [1] => 10012 [2] => 10013 [3] => 10014 [4] => 10015 [5] => 10016 [6] => 10017 [7] => 10018 [8] => 10019 [9] => 10020 [10] => 10021 [11] => 10022 [12] => 10023 [13] => 10024 [14] => 10025 [15] => 10026 [16] => 10027 [17] => 10028 [18] => 10029 [19] => 10030 [20] => 10031 [21] => 10032 [22] => 10033 [23] => 10034 [24] => 10035 [25] => 10036 [26] => 10037 [27] => 10038 [28] => 10039 [29] => 10040 [30] => 10041 [31] => 10042 [32] => 10043 [33] => 10044 [34] => 10045 [35] => 10046 [36] => 10047 [37] => 10048 [38] => 10049 [39] => 10050 [40] => 10051 [41] => 10052 [42] => 10053 [43] => 10054 [44] => 10055 [45] => 10056 [46] => 10057 [47] => 10058 [48] => 10059 [49] => 10060 [50] => 10061 [51] => 10062 [52] => 10063 [53] => 10064 [54] => 10065 [55] => 10066 [56] => 10067 [57] => 10068 [58] => 10069 [59] => 10070 [60] => 10071 [61] => 10072 [62] => 10073 [63] => 10074 [64] => 10075 [65] => 10076 [66] => 10077 [67] => 10078 [68] => 10079 [69] => 10080 [70] => 10092 [71] => 10093 [72] => 10128 )

然后我有一个包含字段 product_id 和 category_id 的表,所以我想传递 $fetchID 的结果并使用 lists() 从 category_id 返回所有值

    // Fetch the category_id where is a product_id
    $catRelation = Db::table('purple_catalog_prods_cats')->whereProductId($fetchID);

    $catRelList = $catRelation->lists('category_id');

这在 print_r 中返回为空

最后我想查询具有 id 和 name 的类别表,并返回所有内容。所以我尝试通过 $catRelList。这不起作用,因为在前面的查询中它返回为空。

    // Fetch the Cat list
    $catList = categoryName::whereId($catRelList)->orderBy('id', 'asc');
    $this->categoryName = $catList->get();

所以我的问题是通过 $fetchID 返回与多个产品 ID 匹配的所有行。当我手动输入产品 ID 时,它会很好地返回该类别。下方查询

 $catRelation = Db::table('purple_catalog_prods_cats')->whereProductId('10011');

现在 10011 在哪里,我想以某种方式传递多个值,例如在 $fetchID 数组中。

这可能吗?有更好的方法吗?

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    将您的 $catRelation 查询更改为使用 whereIn

    $catRelation = Db::table('purple_catalog_prods_cats')->whereIn('product_id', $fetchID);
    

    现在应该可以正确使用您的 ProductID 数组并找到所有匹配的行。 (根据需要更改列名)。

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 2021-12-31
      • 1970-01-01
      • 2016-08-04
      • 2020-04-22
      • 2013-12-13
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      相关资源
      最近更新 更多