ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# thinkphp的显示更新 自动判断是否需要更新 我们已经看到,模型的新增和更新方法都是`save`方法,系统有一套默认的规则来识别当前的数据需要更新还是新增。 - 实例化模型后调用save方法表示新增; - 查询数据后调用save方法表示更新; - save方法传入更新条件后表示更新; 如果你的数据操作比较复杂,可以显式的指定当前调用`save`方法是新增操作还是更新操作。 显式更新数据: ``` <pre class="calibre13">``` <span class="token6">// 实例化模型</span> $user <span class="token">=</span> <span class="token2">new</span> <span class="token3">User</span><span class="token1">;</span> <span class="token6">// 显式指定更新数据操作</span> $user<span class="token">-</span><span class="token">></span><span class="token3">isUpdate</span><span class="token1">(</span><span class="token5">true</span><span class="token1">)</span> <span class="token">-</span><span class="token">></span><span class="token3">save</span><span class="token1">(</span><span class="token1">[</span><span class="token4">'id'</span> <span class="token">=></span> <span class="token5">1</span><span class="token1">,</span> <span class="token4">'name'</span> <span class="token">=></span> <span class="token4">'thinkphp'</span><span class="token1">]</span><span class="token1">)</span><span class="token1">;</span> ``` ``` 显式新增数据: ``` <pre class="calibre13">``` $user <span class="token">=</span> User<span class="token1">:</span><span class="token1">:</span><span class="token2">get</span><span class="token1">(</span><span class="token5">1</span><span class="token1">)</span><span class="token1">;</span> $user<span class="token">-</span><span class="token">></span>name <span class="token">=</span> <span class="token4">'thinkphp'</span><span class="token1">;</span> <span class="token6">// 显式指定当前操作为新增操作</span> $user<span class="token">-</span><span class="token">></span><span class="token3">isUpdate</span><span class="token1">(</span><span class="token5">false</span><span class="token1">)</span><span class="token">-</span><span class="token">></span><span class="token3">save</span><span class="token1">(</span><span class="token1">)</span><span class="token1">;</span> ``` ``` 注意不要在一个模型实例里面做多次更新,会导致部分重复数据不再更新,正确的方式应该是先查询后更新或者使用模型类的`update`方法更新。