【问题标题】:Codeigniter where clause with array带数组的 Codeigniter where 子句
【发布时间】:2018-03-13 15:21:19
【问题描述】:

在 Codeigniter 这是我的控制器 => 愿望清单功能

  $data = array(
  'user_id' => $this->_user_id
  );
  $order_by = "id";
  $query = $this->Database_model->get_data('wishlist','*', $data, $order_by);

  print_r($query);

结果:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [item_id] => 2
            [user_id] => 2
            [tarix] => 2018-03-13 00:00:00
        )

    [1] => stdClass Object
        (
            [id] => 2
            [item_id] => 15
            [user_id] => 2
            [tarix] => 2018-03-13 00:00:00
        )

    [2] => stdClass Object
        (
            [id] => 3
            [item_id] => 10
            [user_id] => 2
            [tarix] => 2018-03-13 00:00:00
        )

)

现在我想获取所有“items”表数据 WHERE id = all these “item_id” inside array。

我尝试使用 foreach 创建新数组并将所有 item_id 推入其中,但在 Codeigniter 中我无法将其用于查询。

【问题讨论】:

  • 您是说您想要where in 声明吗?
  • 您可以使用构建它的查询作为下一个查询的子查询。 where id in(select id ...)
  • @Kisaragi yes where x=y or z=u and etc like this
  • 要为where in 传递一个数组,您的查询需要使用$this-db->where_in('column', $array); 请编辑您的问题以包含get_data()
  • 我不知道Codeigniter,但你可以很容易地在 mysql 中使用子查询,它应该会给你想要的东西。大概select * from items where id in (select item_id from wishlist where ...)

标签: php mysql arrays codeigniter


【解决方案1】:

你可以这样做: 在你的控制器中

$data = array(
    'user_id' => $this->_user_id
);
$order_by = "id";
$query = $this->Database_model->get_data('wishlist','*', $data, $order_by);

$where = array();
foreach ($query as $key => $value)
    array_push($where, $value->item_id); //  Must be item_id

$my_items = $this->Database_model->get_custom_items('items', $where);

在你的模型中

public function get_custom_items($table, $where)
{
    $this->db->select('*');
    $this->db->where_in('id', $where); // Must be id
    return $this->db->get($table)
}

【讨论】:

  • 工作了兄弟,但是您的代码中有两个小错误:在 9. line: id 必须是 item_id,并且在模型中 item_id 必须是 id。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 2018-06-15
  • 2015-07-07
相关资源
最近更新 更多