【问题标题】:Insert a value at a NOT NULL column int in SQL Laravel Eloquent在 SQL Laravel Eloquent 中的 NOT NULL 列 int 处插入一个值
【发布时间】:2021-08-25 03:40:48
【问题描述】:
$add_v = new App\Models\HmsBbrCategory;
$add_v->id->max(id)+1;
$add_v->category_id->max(category_id)+1;
$add_v->category_name='Insert 1';
$add_v->category_description='Insert Desc';
$add_v->created_by='Me';
$add_v->created_datetime=CURRENT_TIMESTAMP;
$add_v->save();

我需要将这个雄辩的数据插入到我的表中,我的前两列 id、category_id 会自动递增,特别是最大值 + 1。

我上面的代码有错误:

Symfony\Component\Debug\Exception\FatalThrowableError
Call to a member function max() on null

我可以在“max()”处做什么才能按预期运行?任何帮助将不胜感激。

【问题讨论】:

  • 你真的需要 category_id 和 id 吗?
  • 是的,我都需要
  • 通常做 max() + 1 并不是特别安全,如果 2 个请求同时尝试插入一条记录会怎样——它们可能都得到相同的 id。

标签: php sql laravel eloquent insert


【解决方案1】:

你有错误

$add_v->category_id->max(category_id)+1;

我认为你需要

$category=App\Models\HmsBbrCategory::orderByDesc('id')->first();

然后

 $add_v->category_id=$category->id+1;

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2014-12-08
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2020-04-15
    • 2019-04-24
    相关资源
    最近更新 更多