thinkphp6Ä£×Ó²»·µ»ØID
½ñÌìÎÒÔÚʹÓÃthinkphp6µÄÄ£×ÓʱÓöµ½ÁËÒ»¸öÎÊÌ⣬¾ÍÊÇÄ£×ÓÔÚ½¨ÉèÊý¾ÝʱûÓзµ»Øid¡£ÕâÈÃÎÒºÜÊÇÒÉÐÄ£¬ÓÉÓÚÔÚÎÒÒÔÇ°µÄ¿ª·¢ÂÄÀúÖУ¬Í¨³£½¨ÉèÊý¾Ýʱ¶¼»á·µ»Øid£¬ÒÔ±ãºóÐøµÄ²Ù×÷¡£ÔÚÕâƪÎÄÕÂÖУ¬ÎÒ½«·ÖÏíÎÒÔõÑù·¢Ã÷Õâ¸öÎÊÌâµÄÔµ¹ÊÔÓÉÒÔ¼°ÔõÑù½â¾öËü¡£
Ê×ÏÈ£¬ÎÒ¼ì²éÁËÎҵĴúÂ룬ȷ±£ÎÒ׼ȷµØʹÓÃÁËÄ£×ӵĽ¨ÉèÒªÁì¡£ÎҵĴúÂëÈçÏ£º
$user = new User(); $user->name = 'John'; $user->email = 'john@example.com'; $user->save(); return $user->id;
µÇ¼ºó¸´ÖÆ
Õâ¶Î´úÂë¿´ÆðÀ´Ó¦¸ÃûÓÐÎÊÌ⣬ÓÉÓÚËüŲÓÃÁËÄ£×ÓµÄsave()ÒªÁ죬Õâ¸öÒªÁìÓ¦¸Ã»á·µ»ØÒ»¸öн¨ÉèµÄÊý¾ÝÐеÄID¡£¿ÉÊÇ£¬µ±ÎÒÔËÐдúÂëʱ£¬ÎÒ·¢Ã÷·µ»ØµÄIDÊÇ0£¬¶ø²»ÊÇÎÒµÄÆÚÍûÖµ¡£ÕâÈÃÎÒºÜÊÇÒÉÐÄ£¬ÓÉÓÚÎÒÒѾÓÃÁ˺ܳ¤Ê±¼äʹÓÃthinkphp¿ò¼Ü£¬²¢ÇÒÎÒÀúÀ´Ã»ÓÐÓöµ½¹ýÕâ¸öÎÊÌâ¡£
½ÓÏÂÀ´£¬ÎÒÉó²éÁËÄ£×ÓµÄÔ´´úÂ룬ÓÈÆäÊÇsave()ÒªÁìµÄʵÏÖ¡£ÎÒ·¢Ã÷Ä£×ÓµÄsave()ÒªÁ챻ʵÏÖΪͨ¹ýŲÓÃcreate()ÒªÁìÀ´½¨ÉèеÄÊý¾ÝÐУ¬È»ºóÔÙÉúÑÄËü£º
public function save($data = [], $where = [], $sequence = null) { if ($this->isExists()) { return $this->update($data, $where, $sequence); } else { $result = $this->create($data); if ($result) { $this->sync($result); } return $result; } }
µÇ¼ºó¸´ÖÆ
ºÜÏÔ×ŵÄÊÇ£¬µ±Êý¾Ý±»½¨Éèʱ£¬Ä£×Ó»áŲÓÃcreate()ÒªÁì¡£ÄÇô£¬ÎÒ¾ÍÈ¥Éó²écreate()ÒªÁìµÄʵÏÖ£¬¿´¿´ËüÊÇ·ñ׼ȷµØ·µ»ØÁËн¨ÉèµÄÊý¾ÝÐеÄID¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
public function create($data = [], $sequence = null) { if (empty($data)) { $data = $this->getOriginData(); } $result = $this->db()->insertGetId($data, $sequence); if (!empty($result)) { $this->exists(true); $this->setRawData([], true); $this->sync($result); $this->trigger('after_create'); return $result; } else { return false; } }
µÇ¼ºó¸´ÖÆ
ͨ¹ý×ÐϸÊÓ²ìcreate()ÒªÁìµÄ´úÂ룬ÎÒ·¢Ã÷Ëüȷʵ»á·µ»Øн¨ÉèÊý¾ÝÐеÄID¡£ÄÇôÎÊÌâ³öÔÚÄÇÀïÄØ£¿
×îºó£¬ÎÒÉó²éÁËÊý¾Ý¿âµÄ±í½á¹¹£¬¼ì²é±íÖеÄID×Ö¶ÎÊÇ·ñ±»×¼È·µØÉèÖÃΪ×ÔÔöÁС£Ð§¹û£¬ÎÒ·¢Ã÷ÎÊÌâ¾Í³öÔÚÕâÀÎÒµÄID×Ö¶ÎûÓÐÉèÖÃΪ×ÔÔöÁС£
Õâ¸öÎÊÌâ¼È¿ÉЦÓÖÞÏÞΣ¬ÓÉÓÚËüµÄÔµ¹ÊÔÓÉÊÇÔÆÔƵļòÆÓ¡£¿ÉÊÇ£¬ËüÒ²Åú×¢ÎúÒ»¸öÊÂʵ£¬ÄǾÍÊÇÎÒÃÇÔÚʹÓÃÄ£×ÓʱҪ×Ðϸ¼ì²éÊý¾Ý¿â±í½á¹¹£¬È·±£ËüÃDZ»×¼È·µØÉèÖá£Ö»ÓÐÕâÑù£¬ÎÒÃDzŻª×¼È·µØʹÓÃÄ£×Ó²¢×èÖ¹·ºÆð²»ÐëÒªµÄÎÊÌâ¡£
ÔÚÎҵݸÀýÖУ¬ÎÒÖ»ÐèÒª½«ID×Ö¶ÎÉèÖÃΪ×ÔÔöÁУ¬²¢ÖØÐÂÔËÐÐÎҵĴúÂ룬¾Í¿ÉÒÔ׼ȷµØ·µ»Øн¨ÉèÊý¾ÝÐеÄIDÁË¡£Õâ¸öÎÊÌâ½â¾öÁËÒÔºó£¬ÎÒ²ÅÒâʶµ½£¬ÔÀ´½¨ÉèÊý¾Ýʱ·µ»ØµÄIDÖµ£¬ÊÇ»ùÓÚÊý¾Ý¿â×ÔÔöÁÐÌØÕ÷ʵÏֵġ£
ÔÚÕâƪÎÄÕÂÖУ¬ÎÒ·ÖÏíÁËÎÒÔõÑù·¢Ã÷Ò»¸öСÎÊÌâµÄÂÄÀú¡£Õâ¸öÎÊÌâµÄȪԴÔÚÓÚÊý¾Ý¿âµÄ±í½á¹¹Ã»ÓÐ׼ȷÉèÖ㬵¼ÖÂÄ£×ÓÔÚ½¨ÉèÊý¾ÝʱûÓзµ»ØID¡£Í¨¹ý×ÐϸµØ¼ì²é´úÂë¡¢Éó²éÄ£×ÓÔ´´úÂë¡¢¼ì²éÊý¾Ý¿â±í½á¹¹£¬ÎÒ×îÖÕ½â¾öÁËÕâ¸öÎÊÌâ¡£ÎÒÏ£ÍûÎÒµÄÂÄÀú¿ÉÒÔ×ÊÖúÆäËû¿ª·¢Õߣ¬ÈÃËûÃǸüºÃµØÃ÷È·thinkphp6¿ò¼ÜµÄÄ£×Ó£¬ÒÔ±ã¸üºÃµØʹÓÃÕâ¸öÇ¿Ê¢µÄ¹¤¾ßÀ´¿ª·¢WebÓ¦ÓóÌÐò¡£
ÒÔÉϾÍÊÇthinkphp6Ä£×Ó²»·µ»ØIDµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡