Laravel在MongoDB中使用引号内的整数,浮点和布尔属性

8yoxcaq7  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(71)

我在Laravel项目中使用MongoDB,遇到了一个问题:我注意到字段ageweightheightconcluded用引号括起来,使它们看起来像字符串:

{
  "_id": {
    "$oid": "64b41ba740f8fc543547b2d3"
  },
  "name": "Michael",
  "age": "20",
  "height": "1.89",
  "weight": "78.79",
  "begin": "2023-07-16",
  "finish": "2023-07-28",
  "concluded": "true",
  "updated_at": {
    "$date": "2023-07-16T16:33:22.423Z"
  },
  "created_at": {
    "$date": "2023-07-16T16:32:39.375Z"
  }
}

字符串
我期望:

{
  "_id": {
    "$oid": "64b41ba740f8fc543547b2d3"
  },
  "name": "Michael",
  "age": 20,
  "height": 1.89,
  "weight": 78.79,
  "begin": "2023-07-16",
  "finish": "2023-07-28",
  "concluded": true,
  "updated_at": {
    "$date": "2023-07-16T16:33:22.423Z"
  },
  "created_at": {
    "$date": "2023-07-16T16:32:39.375Z"
  }
}

2023_07_08_114314_create_persons_table.php

public function up()
{
    Schema::create('persons', function (Blueprint $collection) {
        $collection->string('name');
        $collection->integer('age');
        $collection->double('height');
        $collection->double('weight');
        $collection->date('begin');
        $collection->date('finish');
        $collection->boolean('concluded')->default(false);
        $collection->timestamps();
        $collection->softDeletes();
    });
}

PersonModel.php

class PersonModel extends Model
{
    use HasFactory, SoftDeletes;

    protected $connection = 'mongodb';

    protected $collection = 'persons';

    protected $primary_key = '_id';

    protected $fillable = [
        'name',
        'age',
        'height',
        'weight',
        'begin',
        'finish',
        'concluded',
    ];
}

PersonController.php

public function store(PersonRequest $request)
{
    PersonModel::create(array_map('trim', $request->validated()));

    Log::channel('daily')->info("$request->name was added in system.");

    return redirect('/')->with('success_store', "$request->name was added in system.");
}


我该怎么解决这个问题?

pb3skfrl

pb3skfrl1#

我不认为这会给你带来任何问题,但如果你真的想存储整数,那么简单地使用php类型声明:

SomeModel::create([
    'age' => (int)$request->age ....
]);

字符串
这应该做的魔术,但是的,我会离开它,因为我有点99%肯定它不会造成任何问题:D

相关问题