top-think / top-think/think-orm

v4.0.51 mongo模型onAfterWrite回调数据没有id值

Open
#859 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
437
Forks
188
PR merge metrics
No merged PRs in 30d

Description

示例代码:

class MongoUser extends Model {
    public static function onAfterWrite($user)
    {
        $task = $user->toArray();
        trace($task, 'debug');
    }
}

$data = ['name':'Ben','age':20];
MongoUser::create($data);

发现onAfterWrite($user) 返回的$user 没有主键信息, 取不到$user['id']值

问题出现在 src/Model.php 403-408行

// 写入自增键值
            $key = $db->getAutoInc();
            $val = $db->getLastInsID();
            if ($key && $val) {
                $this->setData($key, $val);
            }

其中 $key = $db->getAutoInc(); $key是空字符串, 本来想自己修复一下改为如下:

// 写入自增键值
            $key = $db->getAutoInc();
            if(empty($key) && $db instanceof db\Mongo){
                $key = $db->getPk();
            }
            $val = $db->getLastInsID();
            if ($key && $val) {
                $this->setData($key, $val);
            }

这样$key='_id'会写入_id的值, 但是在onAfterWrite($user)中取值$user['id']还是无法取到,只要$user['_id']有值

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/Model.php around lines 403-408 and trace the Mongo write path through getAutoInc(), getLastInsID(), getPk(), and onAfterWrite(). Reproduce the MongoUser::create example and inspect the callback payload; done means the written primary-key data is consistently available in the callback according to the model's expected key representation.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, php
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.