duanrang3357 2017-04-06 17:46 采纳率: 0%
浏览 521

如何在插入mongodb之前在模型中设置数据类型? (Laravel-mongodb的)

I get reference from here : https://github.com/jenssegers/laravel-mongodb

I make database and collection in mongodb. I don't make document and column in mongodb. Because it will automatically make the column and data type when insert the data

My controller, you can see this below :

public function create(array $attributes)
{
    ...
    $result = User::create($attributes);
    ...
}

My model, you can see this below :

<?php
...
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; 
use Jenssegers\Mongodb\Eloquent\HybridRelations;

class User extends Eloquent
{
    use HybridRelations;  
    use SoftDeletes;

    protected $connection = 'mongodb';
    public $table = 'users';
    protected $dates = ['deleted_at'];

    public $fillable = [
        ...
        'name',
        ...
    ];

    protected $casts = [
        ...
        'name' => 'string',
        ...
    ];
}

When I insert data into mongodb, data type on mongodb will be automatically created based on input

How to set the data type in the model?

When I have an data type of data input : string

I can set it up to data type : integer in my model

So, data type that is formed in mongodb is integer

  • 写回答

1条回答 默认 最新

  • dongzhuange2625 2018-07-13 23:12
    关注

    MongoDB supports two constructors that can be embedded in the MongoDB document directly, allowing you to specify integer data types. In the MongoDB document, you use the following:

    myField: NumberLong("20372")
    

    to specify that you want "myField" to contain a 64-bit signed integer. If you only want a 32-bit signed integer, then you use:

    myField: NumberInt("20372");
    

    What you have to work out, is how to generate that document text within your PHP script, before passing the document text to the MongoDB driver. Note also that the NumberLong() and NumberInt() constructors take string values, so if your PHP script receives numeric data as strings, you don't have to convert those strings to a numeric type in PHP first: MongoDB will do that for you, when you pass a MongoDB document containing NumberLong() and NumberInt() constructors to the requisite driver functions/methods.

    Of course, to find out how this works, it's best to set up a simple test before launching into full scale editing of your main project, so that when you move on to said editing, you know what changes to make beforehand.

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料