mysql to codeigniter active record help

老子叫甜甜 提交于 2019-12-21 06:28:53

问题


Active record is a neet concept but sometimes I find it difficult to get more complicated queries to work. I find this is at least one place the CI docs are lacking.

Anyway, This is the sql I wrote. It returns the expected results of quests not yet completed by the user that are unlocked and within the users level requirements:

SELECT writing_quests . * 
FROM  `writing_quests` 
LEFT OUTER JOIN members_quests_completed ON members_quests_completed.quest_id = writing_quests.id
LEFT OUTER JOIN members ON members.id = $user_id
WHERE writing_quests.unlocked =1
AND writing_quests.level_required <= $userlevel
AND members_quests_completed.user_id IS NULL 

This is the codeigniter active record query, it returns all quests that are unlocked and within the users level requirement:

$this->db->select('writing_quests.*');
$this->db->from('writing_quests');
$this->db->join('members_quests_completed', 'members_quests_completed.quest_id = writing_quests.id', 'left outer');
$this->db->join('members', "members.id = $user_id", 'left outer');
$this->db->where('writing_quests.unlock', 1);
$this->db->where('writing_quests.level_required <=', $userlevel);   
$this->db->where('members_quests_completed.user_id is null', null, true);

I'm guessing there is something wrong with the way I am asking for Nulls. To be thorough, I figured I'd include everything.


回答1:


I agree that sometimes CI active record can overcomplicate things. Try this for your IS NULL where clause:

$this->db->where('members_quests_completed.user_id IS ','NULL',false);

Try also to enable the profiler or echo the generated query with:

echo $this->db->last_query();

That might shed some light on what the issue is.




回答2:


Sometimes CI makes it a bit complicated... you can always use $this->db->query("your very long query") to simplify a bit (if I recall correctly strings are still escaped - not sure). It's a personal opinion.




回答3:


$this->db->where('column IS NOT NULL')

in your case

$this->db->where('members_quests_completed.user_id is not null');


来源:https://stackoverflow.com/questions/4699070/mysql-to-codeigniter-active-record-help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!