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


How to change carbon date type to string?

编辑:所以我改变了我问题的标题。 它是:为用户迁移内置的时间戳是否与我们在 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');
}
}

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

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更改为字符串。因为我有一个日期转换功能,可以完美地处理发票或我获得的任何其他数据,但对于用户,我遇到了错误。

任何帮助将不胜感激。谢谢。

如果要

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

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

这告诉Laravel您希望将哪些日期作为Carbon对象返回(无(,因此它们都将显示为DateStrings。

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

array('created_at', 'updated_at')

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

抱歉,以上是针对 4.2

在 5.1 中,您只需编写一个属性$dates并为其提供一个空白数组

protected $dates = []

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