<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class Favorites extends Model
{
    public static function table()
    {
        return 'ig_bookfavorites';
    }

	public static function single($className = __CLASS__)
	{
		if (!isset(self::$_self[$className]))
		{
			self::$_self[$className] = new $className;
		}
		
		return self::$_self[$className];
	}

	public function save($array)
	{
	    $sql = "REPLACE INTO `".self::table()."` SET ";
	    $allowFields = array('memberid', 'bid', 'cid', 'sp', 'createdate');
	    $insert = array();
	    foreach ($array as $key => $value)
	    {
	        if (in_array($key, $allowFields))
	        {
	            $insert[$key] = $value;
	        }
	    }
	    $sql .= S::sqlSingle($insert);
	    $this->Db()->query($sql);
	    $this->updateBnum($array['memberid']);
	}
	
	public function updateBnum($uid)
	{
	    // TODO 以后重构这里的代码
	    $bNum = $this->Db()->getValue('SELECT COUNT(*) FROM '.self::table().' WHERE memberid = '.S::sqlEscape($uid));
        if (u('bnum') != $bNum)
        {
            // 防止晚上频繁写表的问题
            $this->Db()->query('UPDATE '.Memberfields::table().' SET bnum='.$bNum.' WHERE uid='.$uid);
        }
	}
}