You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel+October CMS中首次调用::create()方法后模型id字段未正确赋值的问题求助

Laravel+October CMS中首次调用::create()方法后模型id字段未正确赋值的问题求助

大家好,我遇到了一个特别诡异的问题,想请各位帮忙分析下:

我当前的环境是 Laravel 5.5 + October CMS 1.0,搭配 MySQL 5.6 数据库和 PHP 7.4。我的几个模型都用的是默认配置,没修改过任何主键相关的选项,都是整数自增的id作为主键。

问题现象

我用一个极简模型(只有int $id和string $name属性)就能复现这个问题:

  • 当从Twig模板调用控制器方法时,第一次调用::create()返回的模型中$id会被设为0,但数据库里两条记录其实都已经成功创建了;
  • 之后每次调用::create(),返回的模型$id都会正常赋值;
  • 更奇怪的是,这个问题完全不影响我的种子器——在种子器里,第一次调用create后模型就能正常拿到$id。

我已经排查/尝试过的内容

  • 我在网上查了挺久,只找到一个类似的问题,但那个是和Telescope相关的,而我并没有使用Telescope;
  • 数据库表的主键已经正确定义,没有配置问题;
  • 只有第一次调用会出问题,后续所有调用都能正常返回正确的id;
  • 我目前的临时解决方案是:在执行核心逻辑前,先在一个测试用的空表里创建一条 dummy 记录。这个方法虽然很蠢,但能让我继续开发,直到找到根本问题。

我现在完全不知道该从哪里开始排查,所以想问问各位有没有什么思路?


测试用的代码如下:

数据库表SQL

create table if not exists ${your_prefix_}test_table
(
    id           int unsigned auto_increment primary key,
    name          varchar(64)      not null,
    created_at   timestamp        null,
    updated_at   timestamp        null
) collate = utf8mb4_unicode_ci;

Twig模板代码

<div class="modal-body">
    <div class="container">
        {{
            form_open({
                'data-request': __SELF__ ~ "::onTestModel",
                'data-request-success': 'testUpdate(data)'
              })
        }}
        <div class="row">
            {{ form_input( 'text', 'test_input', '') }}
        </div>
        <div class="row ">
            <div>First ID: <span id="first_id"></span></div><div style="margin-left: 1rem">Second ID: <span id="second_id"></span></div>
        </div>
        <div class="d-flex justify-content-around mt-5">
            <div>
                {{ form_button ('Annuler', {'data-dismiss':'modal', 'class': 'btn btn-secondary'} ) }}
            </div>
            <div>
                {{ form_submit ('Suite ...', {'class': 'btn btn-primary' } )}}
            </div>
        </div>
        {{ form_close() }}
    </div>
</div>

<script>
    function testUpdate(data) {
        console.log(data);
        $('#first_id').text(data.first_id);
        $('#second_id').text(data.second_id);
    }
</script>

控制器方法代码

public function onTestModel() {
    $data = input();
    $model1 = TestModel::create([
        'name' => $data['test_input']
    ]);
    $model2 = TestModel::create([
        'name' => $data['test_input']
    ]);

    return ["first_id" => $model1->id, "second_id" => $model2->id];
}

模型代码

<?php

/**
 *
 * @mixin \October\Rain\Database\Model
 * @property int $id
 * @property string $name
 * @method static \October\Rain\Database\Collection|static[] all($columns = ['*'])
 * @method static \October\Rain\Database\Collection|static[] get($columns = ['*'])
 * @method static \October\Rain\Database\Builder|FormationsDuoTypes newModelQuery()
 * @method static \October\Rain\Database\Builder|FormationsDuoTypes newQuery()
 * @method static \October\Rain\Database\Builder|FormationsDuoTypes query()
 * @mixin \Eloquent
 * @noinspection PhpFullyQualifiedNameUsageInspection
 * @noinspection PhpUnnecessaryFullyQualifiedNameInspection
 */
class TestModel extends Model
{
    use \October\Rain\Database\Traits\Validation;

    /**
     * The connection associated with the model.
     *
     * @var string
     */
    protected $connection = 'inx';

    /**
     * @var string The database table used by the model.
     */
    public $table = 'test_table';

    /**
     * @var array Validation rules for attributes
     */
    public $rules = [
        'name' => 'required',
    ];

}

备注:内容来源于stack exchange,提问作者Krystian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 09:39:35