繁体   English   中英

在CodeIgniter中一起使用%like%和JOIN

[英]Using %like% and JOIN together in CodeIgniter

我有三个表:“用户”,“产品”和“ product_types”。 “用户”表存储了有关我的网站用户的所有常规数据(包括id列); “产品”表列出了product_id ,添加产品的用户的user_id以及product_type “ product_types”表具有一个id列(与“ products”表中的product_type int值相对应)和一个varchar name列。

我想在“用户”表中执行%like%搜索,以便当用户搜索产品类型时,它显示具有与搜索到的产品类型匹配的产品的所有用户。 这是我目前在CodeIgniter模型中使用的内容:

$string = urldecode($string);
$this->db->select('users.*');
$this->db->from('users');
$this->db->like('users.company_name',$string,'both');
$this->db->or_like('users.address_1',$string,'both');
$this->db->or_like('users.city',$string,'both');
$this->db->or_like('users.contact',$string,'both');
$this->db->or_like('product_types.name',$string,'both');
$this->db->join('products','users.id = products.client_id');
$this->db->join('product_types','products.product_type = product_types.id');
$this->db->distinct();
$users = $this->db->get();
foreach($users->result() as $user){
   // search result
}

然后,我将其输入到一个foreach语句中...但是,大多数情况下,它仅显示第一行,而其他时候返回却没有结果。 谁能告诉我我要去哪里错了?

我不明白您为什么要进行多个查询,只能在一个查询中完成

    SELECT a.*,b.*,C.* FROM users a LEFT JOIN products b ON b.user_id = a.id LEFT JOIN product_types c ON b.product_type = c.id WHERE a.company_name LIKE '%$string%' OR a.address_1 LIKE '%$string%' OR a.city LIKE '%$string%' a.contact LIKE '%$string%' b.name LIKE '%$string%' 

这将为您提供具有该产品类型的用户的所有产品,请尝试在您的数据库上运行它以查看其运行情况。 然后使用foreach语句获取结果

我要调试查询的方法是首先从顶部查询开始,然后查看结果。 然后,我在其中附加一条语句,然后再次查看结果。

因此,对于您的情况,可以从以下简单情况开始:

$this->db->select('users.*');
$this->db->from('users');

查看结果,然后添加另一条语句:

$this->db->select('users.*');
$this->db->from('users');
$this->db->like('users.company_name',$string,'both');

执行此操作,直到最终形成整个查询。

问题的关键在于您将发现什么语句正在过滤您的其他预期结果。 这也可以向后进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM