简体   繁体   中英

Codeigniter, active record, join

I am currently in the process of building a little game to learn myself some active record (codeigniter) and php. So I am fairly new to all of this.

And of course I've encountered the following challenge on the road.

The challenge is, I have two tables, User_Heroes and Heroes . The table Heroes contains all the heroes a user can choose during his time playing a game (that belong to his faction) and User_Heroes is the table of heroes that the user has already recruited into his service.

The thing I want to do is as follows, I want to make a query that returns a list of heroes that the current user doesn't have in his employ.

To simply get them all I would do this

public function get_faction_heroes($sUser, $hero_faction){
        $oQuery = $this -> db
                        -> select(' id,
                                    hero_name,
                                    hero_faction,
                                    hero_type,
                                    hero_cost,
                                    hero_maintenance,
                                    hero_allowed')
                        -> like('hero_faction',$hero_faction)
                        -> get('heroes')
                        -> result();

        return $oQuery;
    }

Currently I have the following Query build up, but obviously it is wrong as it does not return the list as I expect it to return.

 public function get_faction_heroes($sUser, $hero_faction){
    $oQuery = $this -> db
                    -> select(' h.id,
                                h.hero_name,
                                h.hero_faction,
                                h.hero_type,
                                h.hero_cost,
                                h.hero_maintenance,
                                h.hero_allowed')
                    -> like('h.hero_faction',$hero_faction)
                    -> where_not_in('u.hero_id', $sUser)
                    -> where('h.hero_allowed >', 1)
                    -> join('user_heroes u', 'u.hero_id = h.id', 'left')
                    -> get('heroes h')
                    -> result();

    return $oQuery;
}

As you might notice, some heroes are allowed to be recruited multiple times (hero_allowed > 1).

Perhaps to further clear up the table I've added two images with the current tables

在此处输入图片说明

在此处输入图片说明

$this->db->select('*')->from('Heroes');
$this->db->where('`id` NOT IN (SELECT `hero_id` FROM `User_Heroes`)', NULL, FALSE);
$query=$this->db->get();
return $query->result();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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