


Yii20 In the operation of inserting multiple records, the reason why the old attribute value affects the insertion operation
We sometimes encounter insert and update operations in our projects.
1: For updates:Because if you use $this->setOldAttributes(null);, it means clearing its original record. It will default to the original old attributes that do not exist. Then it thinks that the current record is new, so it An insertion operation will be performed, so we cannot clear its old properties.
2: For insertion:
I print $this during the insertion operation, and it returns me a result like this:
private $_attributes => //这次现在的这条属性 array(7) { 'app_id' => string(6) "100000" 'hour' => string(2) "21" 'stat_day' => string(10) "2015-07-13" 'total' => int(1) 'id' => string(16) "1000002015071321" 'create_time' => int(1449326053) 'update_time' => int(1449326053) } private $_oldAttributes => //此时,它将旧的属性给与了此时的值 array(7) { 'app_id' => string(6) "100000" 'hour' => string(2) "21" 'stat_day' => string(10) "2015-07-13" 'total' => int(1) 'id' => string(16) "1000002015071321" 'create_time' => int(1449326053) 'update_time' => int(1449326053) } private $_related => array(0) { } private $_errors => array(0) { } private $_validators => class ArrayObject#48 (1) { private $storage => array(0) { } } private $_scenario => string(7) "default" private $_events => array(0) { } private $_behaviors => array(0) { } }
When we" When "inserting" the first record, the program will record this record into the old attributes, which is the $_oldAttributes attribute above. Then when we "insert" the second record below, the program will see If there is a value in the $_oldAttributes attribute in the object (no matter what value it is), it defaults to the record already existing, so it will perform an "update" operation, but our current purpose is to let the program perform an "insert" operation. How can we do this? It "updates" that, so at this time we use $this->setOldAttributes(null) to clear $_oldAttributes every time we "insert", Then any time, when a new record is "inserted" later, the program checks that the $_oldAttributes attribute is null, so it naturally follows our operation to "insert" the new record!!
We used $this-> ; SetOLDATTRIBUTES (NULL); Come to clear the old attributes so that the following new records need to be inserted in .
Now the example of my project:
public function actionOfflineUserImport() { $mTempUser = new TempUser(); //取出学霸表中的所有的用户信息 $tempUsers = $mTempUser->find()->select('mobile, truename, weixin, corp, position')->asArray()->all(); if (!$tempUsers) { echo "无用户需要同步\n"; exit(2); } // 遍历所有的用户信息,并将每一项插入到另一个数据库中表中 foreach ($tempUsers as $key => $values) { /<span style="background-color: rgb(0, 153, 0);">/重点在这里</span>: 我们需要每次都重新实例化对象,不然他就会出现上面的情况旧的属性存在,导致他们不认为是添加数据 这里我采用的和上面的不一样,如果你有很多条数据,你传递到model中,需要遍历添加数据,这种情况你可以用上面的清空属性的方法来解决 <span style="color:#CC0000;">$mAccount = new Account(); $mHmcUser = new HmcUser();</span> <span style="color:#CC66CC;">之前我没把这两个对象放到遍历里面,而是放到了方法头部,导致了我添加数据不成功 ??这里一定要注意啊!!!</span> if (!isset($values['mobile']) || !$values['mobile']) { echo "手机号码不存在\n"; exit(3); } $mobile = $values['mobile']; $isMobile = $mAccount->isExistMobile($mobile); if (!$isMobile) { try { $key = 'user:id:pool'; $cache = Yii::$app->cache->instance('base'); if (!($cache->lpop($key))) { echo "获取用户ID失败\n"; exit(4); } else { $values['user_id'] = $cache->lpop($key); } } catch (\Exception $e) { echo "连接redis服务器失败,请稍后重试\n"; exit(5); } $data['user_id'] = $values['user_id']; $data['mobile'] = $values['mobile']; $accountData = $mAccount->addCrm($data, $status = Account::STATUS_UNINIT); $usersData = $mHmcUser->add($values); if (!$accountData) { echo $mobile . "同步account表 => 失败\n"; } else { echo $mobile . "同步account表 => 成功\n"; } if (!$usersData) { echo $mobile . "同步到 user表 => 失败\n"; } else { echo $mobile . "同步到 user表 => 成功\n"; } } } exit(0); }E
Supplement:
Today I knew that one can enter in the command line: echo $ $ $ $ $ ? What is displayed is the status (code) of the last command execution
0 means that the last command was executed successfully
The above introduces the reasons why old attribute values affect the insertion operation when inserting multiple records in Yii20, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
