【问题标题】:Using %like% and JOIN together in CodeIgniter在 CodeIgniter 中同时使用 %like% 和 JOIN
【发布时间】:2011-10-18 01:46:34
【问题描述】:

我有三个表:“users”、“products”和“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 语句中......但它大部分时间只显示第一行 - 其他时候它返回没有结果。谁能告诉我哪里出错了?

【问题讨论】:

  • 尝试打印$this->db->last_query();,它显示了已运行的 SQL 查询。

标签: php codeigniter join search sql-like


【解决方案1】:

我调试查询的方法是首先从顶部查询开始,然后查看结果。然后我将一条语句附加到它并再次查看结果。

所以对于你的情况,你可以从简单的情况开始:

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

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

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

这样做直到最终形成整个查询。

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

【讨论】:

  • 我正在使用 foreach 循环和 result()。我刚刚编辑了我的问题以突出显示这一点
【解决方案2】:

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

    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 语句获取结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多