1

我有3张桌子,

user - contains user_id | username | fullname | email etcc
user_profile - contains entry_id |user_id| profile_image_id| user_location etcc
user_profile_images - contains image_id| user_id | file_path | file_thumb | date etcc

当用户注册时,所有详细信息都进入 users 表,user_id 也被添加到 user_profile 表中,其余设置默认为 NULL,直到用户添加一些配置文件信息。

我在 model_users 中有一个查询来从这三个表中获取所有用户的数据,它是这样的;

$this->db->where('users.user_id', $user_id)->select('*')->from('users');
$this->db->join('user_profile', 'user_profile.user_id = users.user_id', 'left');
$this->db->join('user_profile_images','user_profile_images.image_id = user_profile.profile_image_id','left');

只有当 user_profile 中的 profile_image_id 字段不为空时,即用户上传了图片时,它才能正常工作。在该字段为空的情况下,即使返回所有其他数据,也不返回用户 user_id。

我可以看到为什么会这样,因为我的联接查询需要字段 profile_image_id 但目前我的解决方法是将 user_profile 中的 profile_image_id 设置为 1(默认),这是默认图像,并且 image_id 为 1,user_id 为 0这是一般的默认图像。但我仍然无法克服这样一个事实,即我需要更新该查询以使其不再是黑客攻击。你们有什么想法吗?

4

3 回答 3

4

尝试

$this->db->select('*')->select('users.user_id')->from('users')
                ->join('user_profile', 'user_profile.user_id = users.user_id', 'LEFT')
                ->join('user_profile_images', 'user_profile_images.image_id = user_profile.profile_image_id', 'LEFT')
                ->group_by('users.user_id')
                ->where('users.user_id', $user_id);
                $query = $this->db->get();
于 2012-11-20T21:38:27.237 回答
1

对表使用联接时,您需要所有联接表中的列具有唯一名称。您可以通过 AS 语法添加列别名,或者只检索您需要的列。在您的情况下,错误很可能是由于user_id所有三个表中都存在这一事实。因此,结果就像你所经历的那样。user_id仅在最后一次出现时检索,即如果您的用户已上传图像。我会更改查询,例如:

$this->db->where('users.user_id', $user_id);
$this->db->select('users.*,user_profile.user_location,user_profile_images.filepath'); // and other fields of interest...
$this->db->from('users');
$this->db->group_by('users.user_id'); // very useful for not getting multiple rows/user
$this->db->join('user_profile', 'user_profile.user_id = users.user_id', 'left');
$this->db->join('user_profile_images','user_profile_images.image_id = user_profile.profile_image_id','left'); 
于 2012-11-19T22:42:07.383 回答
0

试试这个。

 $this->db->select("*");
            $this->db->from('table1');
            $this->db->join('table2','table2.id1=table1.id1');
            $this->db->join('table3','table3.id1=table1.id1');
            $query = $this->db->get();
            return $query->result();
于 2017-01-10T06:46:35.493 回答