Laravel 控制器在 save() 处插入两个 id 列

Laravel controller insert two id columns at save()

我正在尝试添加两列:idcategory_id 并且我需要它们的值相同

        $category = new HmsBbrCategory;
        $category->id = increments();
        $category->category_id = id+1;
        $category->category_name = $request->input('category_name');
        $category->category_description = $request->input('category_description');
        $category->save();
        return response()->json([
            'status'=>200,
            'message'=>'Category Added!',
           
        ]);

如您所见,两列 return 均为空,尝试添加两行但当然它们不起作用:

        $category->id = increments();
        $category->category_id = id+1;

两个值都没有形式,我只需要它们自动递增并且相同。我应该在此处更改什么以在 table 中添加一个不是从输入字段中获取的值?

更新

按照建议我增加了 id 但我的控制台错误一直说我的 category_id 是空的:

        $category = new HmsBbrCategory;
        $category->category_name = $request->input('category_name');
        $category->category_description = $request->input('category_description');
        $category->save();
        $category->category_id = $category->id;
        $category->save();

控制台错误:

Failing row contains (3, null, 4, 4).

是不是因为保存函数试图将它插入到 category_id 不需要非空?

更新:

我将 category_id 列设置为不要求不为空,但即使按照建议添加了 save()update,这些列仍然为空。

$category->update(['category_id '=> $category->id]);

$category->category_id = $category->id;
$category->save();

型号:

  protected $fillable = [ "id", "category_id", "category_name", "category_description" ];

完全控制

class BBRCategoryConfigurationController extends Controller {
public function index(){
    return view('frontend.bbr-settings.bbr-category-configuration');
}

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'category_name'=>'required|max:191',
        'category_description'=>'required|max:191',
    ]);
    if($validator->fails())
    {
        return response()->json([
            'status'=>400,
            'errors'=>$validator->messages(),
        ]);
    }
    else {
        $category = new HmsBbrCategory;
        $category->category_name = $request->input('category_name');
        $category->category_description = $request->input('category_description');
        $category->save();
        $category->update(['category_id '=> $category->id]);
        
        return response()->json([
            'status'=>200,
            'message'=>'Category Added!',
           
        ]);
    }
    
}

在您的 database table 中将 id 设置为 auto increment 然后执行以下操作

$category = new HmsBbrCategory;
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->save();

$category->category_id = $category->id;
$category->save();

或 为此,请确保字段名是可填写的

$category = new HmsBbrCategory;
    $category->category_name = $request->input('category_name');
    $category->category_description = $request->input('category_description');
    $category->save();
   
 $category->update(['category_id '=> $category->id]);