Mongo的ORM框架的学习Morphia(十二) morphia的Query和Update

本文详细介绍了使用 Morphia 进行实体更新与查询的方法,包括使用 UpdateOperations 对实体进行属性设置、删除、增加、修改等操作,以及如何通过 Query 实现过滤、排序、限制等查询功能。

转自:http://topmanopensource.iteye.com/blog/1449074

 

一: morphia的Update

 

... /** updates all entities found with the operations*/ 
<T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops);
 /** updates all entities found with the operations; if nothing is found insert the update as an entity if "createIfMissing" is true*/ <T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing); 

/** updates the first entity found with the operations*/
 <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops);

 /** updates the first entity found with the operations; if nothing is found insert the update as an entity if "createIfMissing" is true*/ <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing);

 /** updates the first entity found with the operations; if nothing is found insert the update as an entity if "createIfMissing" is true*/ <T> UpdateResults<T> updateFirst(Query<T> query, T entity, boolean createIfMissing); } 

public interface UpdateOperations<T> { 

/** sets the field value */ 

UpdateOperations<T> set(String fieldExpr, Object value); 
/** removes the field */ 
UpdateOperations<T> unset(String fieldExpr); 

/** adds the value to an array field*/ 

UpdateOperations<T> add(String fieldExpr, Object value); UpdateOperations<T> add(String fieldExpr, Object value, boolean addDups); 

/** adds the values to an array field*/ UpdateOperations<T> addAll(String fieldExpr, List<?> values, boolean addDups); 

/** removes the first value from the array*/ UpdateOperations<T> removeFirst(String fieldExpr); 

/** removes the last value from the array*/
 UpdateOperations<T> removeLast(String fieldExpr);

 /** removes the value from the array field*/ 
UpdateOperations<T> removeAll(String fieldExpr, Object value);

 /** removes the values from the array field*/ 

UpdateOperations<T> removeAll(String fieldExpr, List<?> values);
 /** decrements the numeric field by 1*/ 
UpdateOperations<T> dec(String fieldExpr); 

/** increments the numeric field by 1*/ 
UpdateOperations<T> inc(String fieldExpr); 

/** increments the numeric field by value (negatives are allowed)*/ 
UpdateOperations<T> inc(String fieldExpr, Number value); }The Field Expression

 

初始化:

Morphia morphia = new Morphia(); 
morphia.map(Hotel.class).map(Address.class); 
Datastore datastore = morphia.createDatastore("MorphiaSampleDb"); 
Hotel hotel = new Hotel("Fairmont", 3, new Address("1 Rideau Street", "Ottawa", "K1N8S7", "Canada")); 
datastore.save(hotel); 
UpdateOperations<Hotel> ops; 
 
// This query will be used in the samples to restrict the update operations to only the hotel we just created. 
// If this was not supplied, by default the update() operates on all documents in the collection. 
// We could use any field here but _id will be unique and mongodb by default puts an index on the _id field so this should be fast! 
Query<Hotel> updateQuery = datastore.createQuery(Hotel.class).field("_id").equal(hotel.getId()); 
 
// The Mapper class also provides a public static of the default _id field name for us... 
Query<Hotel> updateQuery = datastore.createQuery(Hotel.class).field(Mapper.ID_KEY).equal(hotel.getId());

 

set/unset

// change the name of the hotel  
ops = datastore.createUpdateOperations(Hotel.class).set("name", "Fairmont Chateau Laurier");  
datastore.update(updateQuery, ops);    
// also works for embedded documents, change the name of the city in the address  
ops = datastore.createUpdateOperations(Hotel.class).set("address.city", "Ottawa");  
datastore.update(updateQuery, ops);    
// remove the name property from the document  
// causes the next load of the Hotel to have name = null  
ops = datastore.createUpdateOperations(Hotel.class).unset("name");  
datastore.update(updateQuery, ops);

 

inc/dec

// increment 'stars' by 1  
ops = datastore.createUpdateOperations(Hotel.class).inc("stars");  
datastore.update(updateQuery, ops);    
// increment 'stars' by 4  
ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 4);  
datastore.update(updateQuery, ops);    
// decrement 'stars' by 1  
ops = datastore.createUpdateOperations(Hotel.class).dec("stars");  
// same as .inc("stars", -1)  
datastore.update(updateQuery, ops);    
// decrement 'stars' by 4  
ops = datastore.createUpdateOperations(Hotel.class).inc("stars", -4);  
datastore.update(updateQuery, ops);

 

add/All

// push a value onto an array() (+v 0.95)   
// same as .add("roomNumbers", 11, false)  
ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11);  
datastore.update(updateQuery, ops);  // [ 11 ] 
// Performing array operations on a non-array property causes mongodb to throw an error.
ops = datastore.createUpdateOperations(Hotel.class).set("roomNumbers", 11);  
datastore.update(updateQuery, ops);    
// causes error since 'roomNumbers' is not an array at this point  
ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, false);  
datastore.update(updateQuery, ops);  // causes error    
// delete the property  
ops = datastore.createUpdateOperations(Hotel.class).unset("roomNumbers");  
datastore.update(updateQuery, ops);    
// use the 3rd parameter to add duplicates    
// add to end of array, same as add()  
ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, false);  
datastore.update(updateQuery, ops);  // [ 11 ]    
// no change since its a duplicate... doesn't cause error  
ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, false);  
datastore.update(updateQuery, ops);  // [ 11 ]    
// push onto the end of the array  
ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 12, false);  
datastore.update(updateQuery, ops); // [ 11, 12 ]    
// add even if its a duplicate  
ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, true);  
datastore.update(updateQuery, ops); // [ 11, 12, 11 ]

 

removeFirst/Last/All

//given roomNumbers = [ 1, 2, 3 ]  
ops = datastore.createUpdateOperations(Hotel.class).removeFirst("roomNumbers");  
datastore.update(updateQuery, ops);  // [ 2, 3 ]      
//given roomNumbers = [ 1, 2, 3 ]  
ops = datastore.createUpdateOperations(Hotel.class).removeLast("roomNumbers");  
datastore.update(updateQuery, ops);  // [ 1, 2 ]  
ops = datastore.createUpdateOperations(Hotel.class).removeLast("roomNumbers");  
datastore.update(updateQuery, ops);  // [ 1 ]  
ops = datastore.createUpdateOperations(Hotel.class).removeLast("roomNumbers");  
datastore.update(updateQuery, ops);  // []   empty array      
//given roomNumbers = [ 1, 2, 3, 3 ]  
ops = datastore.createUpdateOperations(Hotel.class).removeAll("roomNumbers", 3);  
datastore.update(updateQuery, ops);  // [ 1, 2 ]    
//given roomNumbers = [ 1, 2, 3, 3 ]  
ops = datastore.createUpdateOperations(Hotel.class).removeAll("roomNumbers", Arrays.asList(2, 3));  
datastore.update(updateQuery, ops);  // [ 1 ]

 

Multiple Operations

//You can also perform multiple update operations within a single update.
//set city to Ottawa and increment stars by 1  
ops = datastore.createUpdateOperations(Hotel.class).set("city", "Ottawa").inc("stars");  
datastore.update(updateQuery, ops);    
//if you perform multiple operations in one command on the same property, results will vary  
ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50).inc("stars");  //increments by 1  
ops = datastore.createUpdateOperations(Hotel.class).inc("stars").inc("stars", 50);  //increments by 50    
//you can't apply conflicting operations to the same property  
ops = datastore.createUpdateOperations(Hotel.class).set("stars", 1).inc("stars", 50); //causes error

 

updateFirst method

//In the default driver and shell this is the default behavior. In Morphia we feel like updating all the results of the query is a better default (see below).
//{ name: "Fairmont", stars: 5}, { name: "Last Chance", stars: 3 }
ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50);    
// (+v 0.95 now takes into account the order())  
// morphia exposes a specific updateFirst to update only the first hotel matching the query  
datastore.updateFirst(datastore.find(Hotel.class).order("stars"), ops);  // update only Last Chance  
datastore.updateFirst(datastore.find(Hotel.class).order("-stars"), ops); // update only Fairmont
//default shell version is to match first  
//shell version has a multi to indicate to update all matches, not just first  
//to mimic morphia operation, set multi = false  
db.collection.update( criteria, objNew, upsert, multi );

 

update method

ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50);    
// morphia default update is to update all the hotels  datastore.update(datastore.createQuery(Hotel.class), ops);  //increments all hotels
//equivalent morphia shell version is... upsert = false, multi = true  
db.collection.update( criteria, objNew, false, true );

 

createIfMissing (overload parameter)

//all of the update methods are overloaded and accept a "createIfMissing" parameter
ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50);    
//update, if not found create it  
datastore.updateFirst(datastore.createQuery(Hotel.class).field("stars").greaterThan(100), ops, true);      
// creates { "_id" : ObjectId("4c60629d2f1200000000161d"), "stars" : 50 }
// equivalent morphia shell version is... upsert = true  
db.collection.update( criteria, objNew, true, multi );

 

 

二: morphia的Query

 

Introduction

The Query interface is pretty straight forward. It allows for certain filter criteria (based on fields), sorting, an offset, and limiting of the number of results.

The query implementation also implements the the  QueryResults   interface which allows access to the data from the query.

Filter

The generic  .filter(criteria, value)  syntax is supported. The criteria is a composite of the field name and the operator ("field >", or "field in"). All criteria are implicitly combined with a logical "and".

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 );

 

 

Finding entities where foo is between 12 and 30 would look like this:

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 ). filter ( "foo <" ,   30 );

 

 

Operators

The operators used in  filter(...)   match the MongoDB query operators very closely.

 

operatormongo op
=$eq
!=, <>$ne
>, <, >=,<=$gt, $lt, $gte, $lte
in$in
nin$nin
elem$elemMatch
exists$exists
all$all
size$size
......

Fluent Interface

Along with the  .filter(...)   method there are fluent query methods as well. These provide a more readable (like in the english language sense) form.

The fluent interface works by starting with  field(name) . Then any of the following methods can be added to form the filtering part of the criteria.

Query   q  =   ds . createQuery ( MyEntity . class ). field ( "foo" ). equal ( 1 );     q . field ( "bar" ). greaterThan ( 12 );   q . field ( "bar" ). lessThan ( 40 );

 

 

Methods

 

methodoperationcomment
exists$exists
doesNotExist$exists
greaterThan, greaterThanOrEq, lessThan, lessThanOrEq$gt, $gte, $lt, $lte
equal, notEqual$eq, $ne
hasThisOne$eq
hasAllOf$all
hasAnyOf$in
hasNoneOf$nin
hasThisElement$elemMatch
sizeEq$size

Geo-spatial

All of the geo-spatial query methods break down into "near, and within". All of the  near   queries will produce results in order of distance, closest first. All of the methods below also accept a final parameter of  spherical   to indicate if they should use the new  $sphere   option.

methodoperationcomment
near(x,y)$near
near(x,y,r)$near(w/maxDistance of r)
within(x,y,r)$within + $center
within(x1,y1,x2,y2)$within + $box

@Entity    static   private   class   Place   {            @Id   protected   ObjectId   id ;            protected   String   name  =   "" ;           @Indexed ( IndexDirection . GEO2D )            protected   double []   loc  =   null ;                      public   Place ( String   name , double []   loc )   {                    this . name  =   name ;                    this . loc  =   loc ;   }              private   Place ()   {}    }      Place place1  =   new   Place ( "place1" ,   new   double []   { 1 , 1 });   ds . save ( place1 );      Place   found  = ds . find ( Place . class ). field ( "loc" ). near ( 0 ,   0 ). get ();

 

 

Or

Using the fluent query interface you can also do "or" queries like this:

Query < Person >   q  =   ad . createQuery ( Person . class );   q . or (           q . criteria ( "firstName" ). equal ( "scott" ),           q . criteria ( "lastName" ). equal ( "scott" )    );

 

 

Note : In this example the method  criteria   is used. It you use  field}} as one of the {{{or   parameters then you will get a compiler error.

Fields

Field names can be used much like they can in  native mongodb queries , with  "dot" notation .

Query   q  =   ds . createQuery ( Person . class ). field ( "addresses.city" ). equal ( "San Francisco" );    //or with filter, or with this helper method    Query   q  =   ds . find ( Person . class ,   "addresses.city" ,   "San Francisco" );

 

 

Validation

Validation is done on the field names, and data types used. If a field name is not found on the java class specified in the query then an exception is thrown. If the field name is in "dot" notation then each part of the expression is checked against your java object graph (with the exception of a map, where the key name is skipped).

Problems in the data type (comparing the field type and parameter type) are logged as warnings since it is possible that the server can coerce the values, or that you meant to send something which didn't seem to make sense; The server uses the byte representation of the parameter so some values can match even if the data types are different (numbers for example).

Disabling Validation

Validation can be disabled by calling  disableValidation()   as the beginning of the query definition, or anywhere within you query.

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). disableValidation ();      //or it can be disabled for just one filter      Query   q  =   ds . createQuery ( MyEntity . class ). disableValidation (). filter ( "someOldField" , value ). enableValidation (). filter ( "realField" ,   otherVal );

 

 

Sort

You can sort by a field, or multiple fields in ascending or descending order.

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 ). order ( "dateAdded" );    ...   // desc order    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 ). order ( "-dateAdded" );    ...   // asc dateAdded, desc foo    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 ). order ( "dateAdded, -foo" );

 

 

Limit

You can also limit for the number of elements.

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 ). limit ( 100 );

 

 

Offset (skip)

You can also ask the server to skip over a number of elements on the server by specifying an offset value for the query. This will less efficient than a range filter using some field, for pagination for example.

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 ). offset ( 1000 );

 

 

Ignoring Fields

MongoDB also supports only returning certain fields. This is a little strange in application but it is an important way to trim parts off of embedded graphs. This will lead to partial entities and should be used sparingly, if at all.

Datastore   ds  =   ...    MyEntity   e  =   ds . createQuery ( MyEntity . class ). retrievedFields ( true ,   "foo" ). get ();     val  = e . getFoo ();   // only field returned      ...      MyEntity   e  =   ds . createQuery ( MyEntity . class ). retrievedFields ( false , "foo" ). get ();     val  =   e . getFoo ();   // only field not returned

 

 

The field name argument (the last arg) can be a list of strings or a string array:

MyEntity   e  =   ds . createQuery ( MyEntity . class ). retrievedFields ( true ,   "foo" ,   "bar" ). get ();     val  =   e . getFoo ();   // fields returned   vak  =   e . getBar ();   // fields returned

 

 

Returning Data

To return your data just call one of the  QueryResults   methods. None of these methods affect the Query. They will leave the Query alone so you can continue to use it to retrieve new results by calling these methods again.

 

methoddoes
get()returns the first Entity -- using limit(1)
asList()return all items in a List -- could be costly with large result sets
fetch()explicit method to get Iterable instance
asKeyList()return all items in a List of their  Key<T>   -- This only retrieves the  id field from the server.
fetchEmptyEntities()Just like a  fetch()   but only retrieves, and fills in the id field.

Datastore   ds  =   ...    Query   q  =   ds . createQuery ( MyEntity . class ). filter ( "foo >" ,   12 );      //single entity    MyEntity   e  = q . get ();     e  =   q . sort ( "foo" ). get ();      //for    for   ( MyEntity   e  :   q )      print ( e );      //list    List < MyEntity >   entities  =   q . asList ();

 

 

修复一下这个函数 新增一个字段, 输赢整数 # 赔付状态 -1:闲输 1:正常赔付玩家赢 2 部分赔付玩家赢 3 喝水赔付玩家赢 def calculate_winning(agent_id, draw_period, winning_numbers, return_principal_on_loss=True): """ 计算某一期所有投注的赔付结果,并在结果中包含 username balance :param agent_id: 代理ID :param draw_period: 期号 :param winning_numbers: 开奖号码(格式如 "7,8,6,9") :param mysql: MySQL 数据库连接对象 :param return_principal_on_loss: 是否在部分赔付时返还本金(默认 True) :return: 赔付明细列表,每个条目包含 user_id, username, bet_amount, win_amount, status, balance 等字段 """ cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) #cursor = mysql.cursor(dictionary=True) #这个可以调试 # 1. 获取投注记录并结合 users 表获取 username balance query_bets = """ SELECT b.*, u.username, u.balance FROM bets b JOIN users u ON b.user_id = u.id WHERE b.agent_id = %s AND b.draw_period = %s """ cursor.execute(query_bets, (agent_id, draw_period)) bets = cursor.fetchall() if not bets: print("没有找到相关下注记录") return [] # 2. 获取庄家信息 query_bank = """ SELECT * FROM banks WHERE agent_id = %s """ cursor.execute(query_bank, (agent_id,)) bank = cursor.fetchone() if not bank: print("没有找到对应庄家信息") return [] bank_balance = float(bank['balance']) # 3. 获取赔率配置 query_agent = """ SELECT odds_settings FROM agents WHERE id = %s """ cursor.execute(query_agent, (agent_id,)) agent = cursor.fetchone() if not agent or not agent['odds_settings']: print("代理配置缺失") return [] odds_settings = json.loads(agent['odds_settings'])["赔率_限红"] code_to_odds = {} code_to_tie_rule = {} for key in odds_settings: point_code = str(odds_settings[key]['代码']) code_to_odds[point_code] = float(odds_settings[key]['赔率']) code_to_tie_rule[point_code] = bool(odds_settings[key].get('同点庄赢', False)) # 4. 解析开奖号码 try: winning_list = [int(num) for num in winning_numbers.split(',')] except: print("开奖号码格式错误") return [] if len(winning_list) < 2: print("开奖号码数据不完整") return [] banker_point = int(winning_list[0]) player_points = [int(p) for p in winning_list[1:]] # 5. 按 bet_type 分组 def get_player_index(bet): try: return int(bet['bet_type'].replace('门', '')) except: return -1 bets_by_position = {} for bet in bets: pos = get_player_index(bet) if pos not in bets_by_position: bets_by_position[pos] = [] bets_by_position[pos].append(bet) # 6. 构造有效门次并排序 valid_positions = [ (idx + 1, player_points[idx]) for idx in range(len(player_points)) if (idx + 1) in bets_by_position ] sorted_positions = sorted(valid_positions, key=lambda x: x[1], reverse=True) results = [] # 7. 先杀阶段:比庄小或平局 print("【第一阶段】开始:先杀(比庄小或平局)") for idx, player_point in enumerate(player_points, start=1): if idx not in bets_by_position: continue current_bets = bets_by_position.get(idx, []) for bet in current_bets: amount = float(bet['amount']) user_id = bet['user_id'] username = bet['username'] balance = float(bet['balance']) # 用户原始余额 bet_code = str(player_point) if player_point < banker_point: # 比庄小,输 bank_balance += amount total_win = 0 if not return_principal_on_loss else amount status = "输(先杀)" reason = f"玩家点数 {player_point} 小于庄家点数 {banker_point}" results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": 0, "status": status, "reason": reason, "balance": balance + total_win }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (balance + total_win, user_id)) elif player_point == banker_point: tie_rule = code_to_tie_rule.get(bet_code, False) if tie_rule: max_payout = amount * code_to_odds.get(bet_code, 1.0) if bank_balance >= max_payout: win_amount = max_payout bank_balance -= win_amount total_win = win_amount status = "正常赔付(平局且闲赢)" reason = f"平局,但赔率配置允许闲赢,赔付 {max_payout:.2f}" elif bank_balance > 0: win_amount = bank_balance bank_balance -= win_amount total_win = win_amount if return_principal_on_loss: total_win += amount status = "部分赔付(平局且闲赢)" reason = f"平局,但庄家余额不足,赔付 {win_amount:.2f}" + ( f",返还本金 {amount:.2f}" if return_principal_on_loss else "") else: total_win = amount if return_principal_on_loss else 0 status = "喝水赔付(返还本金)" reason = "平局且庄家无余额,仅返还本金" results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": code_to_odds.get(bet_code, 1.0), "status": status, "reason": reason, "balance": balance + total_win }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (balance + total_win, user_id)) else: bank_balance += amount total_win = 0 if not return_principal_on_loss else amount results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": 0, "status": "输(平局且庄赢)", "reason": f"平局且赔率配置规定庄赢,没收投注金额 {amount:.2f}", "balance": balance + total_win }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (balance + total_win, user_id)) print(f"当前庄家余额:{bank_balance:.2f}") # 8. 后赔阶段:从高到低赔付 print("【第二阶段】开始:后赔(点数从高到低)") for idx, player_point in sorted_positions: if player_point <= banker_point: continue current_bets = bets_by_position.get(idx, []) for bet in current_bets: amount = float(bet['amount']) user_id = bet['user_id'] username = bet['username'] balance = float(bet['balance']) # 原始余额 bet_code = str(player_point) odds = code_to_odds.get(bet_code, 1.0) max_payout = amount * odds if bank_balance >= max_payout: win_amount = max_payout bank_balance -= win_amount total_win = win_amount status = "正常赔付" reason = f"玩家点数 {player_point} 大于庄家点数 {banker_point},赔付 {win_amount:.2f}" elif bank_balance > 0: win_amount = bank_balance bank_balance -= win_amount total_win = win_amount if return_principal_on_loss: total_win += amount status = "部分赔付(庄家余额不足)" reason = f"玩家点数 {player_point} 大于庄家点数 {banker_point},但庄家余额不足,赔付 {win_amount:.2f}" + ( f",返还本金 {amount:.2f}" if return_principal_on_loss else "" ) else: total_win = amount if return_principal_on_loss else 0 status = "喝水赔付(返还本金)" reason = "玩家点数大于庄家,但庄家无余额,仅返还本金" new_balance = balance + total_win results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": odds if total_win != amount else 1.0, "status": status, "reason": reason, "balance": new_balance, "player_point":player_point }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (new_balance, user_id)) print(f"门次:{idx}, 点数:{player_point}, 当前庄家余额:{bank_balance:.2f}") if bank_balance <= 0: print("庄家余额已耗尽,后续投注仅返还本金(喝水)") # 9. 更新庄家余额 update_bank_query = "UPDATE banks SET balance = %s WHERE id = %s" cursor.execute(update_bank_query, (bank_balance, bank['id'])) cursor.close() print(f"\n最终庄家余额:{bank_balance:.2f}") print(f"赔付明细:\n{json.dumps(results, indent=4, ensure_ascii=False)}") return format_payout_result(results, draw_period)
07-02
你希望在赔付状态中新增一个字段,表示输赢整数(例如:-1、1、2、3),我们可以根据不同的赔付状态设置这个字段。下面是修复并新增该字段的代码: ```python import json import MySQLdb def calculate_winning(agent_id, draw_period, winning_numbers, mysql, return_principal_on_loss=True): """ 计算某一期所有投注的赔付结果,并在结果中包含 username balance :param agent_id: 代理ID :param draw_period: 期号 :param winning_numbers: 开奖号码(格式如 "7,8,6,9") :param mysql: MySQL 数据库连接对象 :param return_principal_on_loss: 是否在部分赔付时返还本金(默认 True) :return: 赔付明细列表,每个条目包含 user_id, username, bet_amount, win_amount, status, balance 等字段 """ cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) # 1. 获取投注记录并结合 users 表获取 username balance query_bets = """ SELECT b.*, u.username, u.balance FROM bets b JOIN users u ON b.user_id = u.id WHERE b.agent_id = %s AND b.draw_period = %s """ cursor.execute(query_bets, (agent_id, draw_period)) bets = cursor.fetchall() if not bets: print("没有找到相关下注记录") return [] # 2. 获取庄家信息 query_bank = """ SELECT * FROM banks WHERE agent_id = %s """ cursor.execute(query_bank, (agent_id,)) bank = cursor.fetchone() if not bank: print("没有找到对应庄家信息") return [] bank_balance = float(bank['balance']) # 3. 获取赔率配置 query_agent = """ SELECT odds_settings FROM agents WHERE id = %s """ cursor.execute(query_agent, (agent_id,)) agent = cursor.fetchone() if not agent or not agent['odds_settings']: print("代理配置缺失") return [] odds_settings = json.loads(agent['odds_settings'])["赔率_限红"] code_to_odds = {} code_to_tie_rule = {} for key in odds_settings: point_code = str(odds_settings[key]['代码']) code_to_odds[point_code] = float(odds_settings[key]['赔率']) code_to_tie_rule[point_code] = bool(odds_settings[key].get('同点庄赢', False)) # 4. 解析开奖号码 try: winning_list = [int(num) for num in winning_numbers.split(',')] except: print("开奖号码格式错误") return [] if len(winning_list) < 2: print("开奖号码数据不完整") return [] banker_point = int(winning_list[0]) player_points = [int(p) for p in winning_list[1:]] # 5. 按 bet_type 分组 def get_player_index(bet): try: return int(bet['bet_type'].replace('门', '')) except: return -1 bets_by_position = {} for bet in bets: pos = get_player_index(bet) if pos not in bets_by_position: bets_by_position[pos] = [] bets_by_position[pos].append(bet) # 6. 构造有效门次并排序 valid_positions = [ (idx + 1, player_points[idx]) for idx in range(len(player_points)) if (idx + 1) in bets_by_position ] sorted_positions = sorted(valid_positions, key=lambda x: x[1], reverse=True) results = [] # 7. 先杀阶段:比庄小或平局 print("【第一阶段】开始:先杀(比庄小或平局)") for idx, player_point in enumerate(player_points, start=1): if idx not in bets_by_position: continue current_bets = bets_by_position.get(idx, []) for bet in current_bets: amount = float(bet['amount']) user_id = bet['user_id'] username = bet['username'] balance = float(bet['balance']) # 用户原始余额 bet_code = str(player_point) if player_point < banker_point: # 比庄小,输 bank_balance += amount total_win = 0 if not return_principal_on_loss else amount status = "输(先杀)" reason = f"玩家点数 {player_point} 小于庄家点数 {banker_point}" win_int = -1 # 新增字段:闲输 results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": 0, "status": status, "reason": reason, "balance": balance + total_win, "win_int": win_int # 新增字段 }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (balance + total_win, user_id)) elif player_point == banker_point: tie_rule = code_to_tie_rule.get(bet_code, False) if tie_rule: max_payout = amount * code_to_odds.get(bet_code, 1.0) if bank_balance >= max_payout: win_amount = max_payout bank_balance -= win_amount total_win = win_amount status = "正常赔付(平局且闲赢)" reason = f"平局,但赔率配置允许闲赢,赔付 {max_payout:.2f}" win_int = 1 # 正常赔付玩家赢 elif bank_balance > 0: win_amount = bank_balance bank_balance -= win_amount total_win = win_amount if return_principal_on_loss: total_win += amount status = "部分赔付(平局且闲赢)" reason = f"平局,但庄家余额不足,赔付 {win_amount:.2f}" + ( f",返还本金 {amount:.2f}" if return_principal_on_loss else "") win_int = 2 # 部分赔付玩家赢 else: total_win = amount if return_principal_on_loss else 0 status = "喝水赔付(返还本金)" reason = "平局且庄家无余额,仅返还本金" win_int = 3 # 喝水赔付玩家赢 results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": code_to_odds.get(bet_code, 1.0), "status": status, "reason": reason, "balance": balance + total_win, "win_int": win_int # 新增字段 }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (balance + total_win, user_id)) else: bank_balance += amount total_win = 0 if not return_principal_on_loss else amount results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": 0, "status": "输(平局且庄赢)", "reason": f"平局且赔率配置规定庄赢,没收投注金额 {amount:.2f}", "balance": balance + total_win, "win_int": -1 # 闲输 }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (balance + total_win, user_id)) print(f"当前庄家余额:{bank_balance:.2f}") # 8. 后赔阶段:从高到低赔付 print("【第二阶段】开始:后赔(点数从高到低)") for idx, player_point in sorted_positions: if player_point <= banker_point: continue current_bets = bets_by_position.get(idx, []) for bet in current_bets: amount = float(bet['amount']) user_id = bet['user_id'] username = bet['username'] balance = float(bet['balance']) # 原始余额 bet_code = str(player_point) odds = code_to_odds.get(bet_code, 1.0) max_payout = amount * odds if bank_balance >= max_payout: win_amount = max_payout bank_balance -= win_amount total_win = win_amount status = "正常赔付" reason = f"玩家点数 {player_point} 大于庄家点数 {banker_point},赔付 {win_amount:.2f}" win_int = 1 # 正常赔付玩家赢 elif bank_balance > 0: win_amount = bank_balance bank_balance -= win_amount total_win = win_amount if return_principal_on_loss: total_win += amount status = "部分赔付(庄家余额不足)" reason = f"玩家点数 {player_point} 大于庄家点数 {banker_point},但庄家余额不足,赔付 {win_amount:.2f}" + ( f",返还本金 {amount:.2f}" if return_principal_on_loss else "" ) win_int = 2 # 部分赔付玩家赢 else: total_win = amount if return_principal_on_loss else 0 status = "喝水赔付(返还本金)" reason = "玩家点数大于庄家,但庄家无余额,仅返还本金" win_int = 3 # 喝水赔付玩家赢 new_balance = balance + total_win results.append({ "user_id": user_id, "username": username, "bet_amount": amount, "win_amount": total_win, "odds": odds if total_win != amount else 1.0, "status": status, "reason": reason, "balance": new_balance, "player_point": player_point, "win_int": win_int # 新增字段 }) update_query = "UPDATE bets SET win_amount = %s WHERE id = %s" cursor.execute(update_query, (total_win, bet['id'])) # 新增:更新用户余额 update_user_balance_query = "UPDATE users SET balance = %s WHERE id = %s" cursor.execute(update_user_balance_query, (new_balance, user_id)) print(f"门次:{idx}, 点数:{player_point}, 当前庄家余额:{bank_balance:.2f}") if bank_balance <= 0: print("庄家余额已耗尽,后续投注仅返还本金(喝水)") # 9. 更新庄家余额 update_bank_query = "UPDATE banks SET balance = %s WHERE id = %s" cursor.execute(update_bank_query, (bank_balance, bank['id'])) cursor.close() print(f"\n最终庄家余额:{bank_balance:.2f}") print(f"赔付明细:\n{json.dumps(results, indent=4, ensure_ascii=False)}") return format_payout_result(results, draw_period) ``` ### 新增字段说明: - `win_int` 字段表示赔付的状态码: - `-1`: 闲输 - `1`: 正常赔付玩家赢 - `2`: 部分赔付玩家赢 - `3`: 喝水赔付玩家赢 这个字段可以用于前端展示、日志分析、或者数据库存储。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值