首页 文章

如何将碳日期类型更改为字符串?

提问于
浏览
2

编辑:所以我改变了我的问题的 Headers . 它是:内置的用户迁移时间戳与我们在Laravel中创建的其他迁移不同吗?

好的,这就是事情 . 开箱即用的Laravel有用户迁移 . 所以我没有创造任何 . 我需要一张发票表,所以我为此进行了迁移 . 以下是两个:

class CreateUsersTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
}
}

发票迁移:

class CreateInvoicesTable extends Migration
{

public function up()
{
    Schema::create('invoices', function (Blueprint $table) {
        $table->unsignedInteger('id')->unique();
        $table->unsignedInteger('user_id')->index();
        $table->longText('url');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('invoices');
}
}

我在那里放了一些初始数据 . 现在,当我为每个人vardump created_at时,我得到了不同的结果!!我刚刚测试如下,结果如下:

foreach ($users as $user)
    {
        return var_dump($user->created_at);
    }

结果是:

object(Carbon\Carbon)#185 (3) { ["date"]=> string(19) "2015-11-08 14:50:29" ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Asia/Tehran" }

但对于发票:

foreach ($invoices as $invoice)
    {
        return var_dump($invoice->created_at);

    }

我明白了:

string(19) "2015-11-09 11:15:55"

现在我真的不在乎为什么会这样 . 如何将用户时间戳created_at更改为字符串 . 因为我有一个日期转换功能,完全适用于发票或我得到的任何其他数据,但对于我收到错误的用户 .

任何帮助,将不胜感激 . 非常感谢你 .

1 回答

  • 1

    如果要覆盖Laravel Carbon对象,请在模型中编写要覆盖的以下函数 .

    public function getDates() {
        return array();
    }
    

    这告诉Laravel你希望作为Carbon对象返回的日期(无)因此它们都将作为DateStrings出现

    希望这会有所帮助 - 但请注意,这将影响模型中的每个日期 . 如果您希望将某些日期视为Carbon对象,请将它们添加到数组中

    array('created_at', 'updated_at')

    Doc http://laravel.com/docs/4.2/eloquent#date-mutators

    道歉,上面是4.2

    在5.1中,你可以只写一个属性 $dates 并给它一个空白数组

    protected $dates = []

    docs http://laravel.com/docs/5.1/eloquent-mutators#date-mutators

相关问题