大家.
我是laravel的新手.
这是我的问题:
这可以自定义时间戳名称
const CREATED_AT = 'created';
const UPDATED_AT = 'updated';
Run Code Online (Sandbox Code Playgroud)
这可以禁用时间戳
public $timestamps = false;
Run Code Online (Sandbox Code Playgroud)
我只想使用created_at,怎么做?
Jos*_*ber 74
Eloquent不提供开箱即用的功能,但您可以使用creating事件回调自行创建:
class User extends Eloquent {
public $timestamps = false;
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->created_at = $model->freshTimestamp();
});
}
}
Run Code Online (Sandbox Code Playgroud)
Rod*_*ira 47
使用在顶部:
const UPDATED_AT = null;
Run Code Online (Sandbox Code Playgroud)
对于'created_at'字段,您可以使用:
const CREATED_AT = null;
Run Code Online (Sandbox Code Playgroud)
LARAVEL 5.5.0 - 5.5.5更新
这在Laravel 5.5.0中被打破(并在5.5.5中再次修复).
如果您使用的是5.5.x,请确保您使用的是最新版本.
如果由于某种原因你不能使用最新版本,这是一个解决方法.
将public $ timestamps设置为false:
public $timestamps = false;
Run Code Online (Sandbox Code Playgroud)
并在必要时:
public function setCreatedAtAttribute($value) {
$this->attributes['created_at'] = \Carbon\Carbon::now();
}
Run Code Online (Sandbox Code Playgroud)
要么
public function setUpdatedAtAttribute($value) {
$this->attributes['updated_at'] = \Carbon\Carbon::now();
}
Run Code Online (Sandbox Code Playgroud)
当需要两个字段"created_at"和"updated_at"时,您当然不需要做任何事情;)
Abr*_*hin 23
我有更好的回答这里的Laravel 5.2或以上.
你可以在模特中使用它 -
class User extends Model
{
public $timestamps = false; // disable all behavior
public $timestamps = true; // enable all behavior
public $timestamps = [ "created_at" ]; // enable only to created_at
public $timestamps = [ "updated_at" ]; // enable only to updated_at
public $timestamps = [ "created_at", "updated_at" ]; // same as true, enable all behavior
}
Run Code Online (Sandbox Code Playgroud)
那么,对于你的问题,答案是 -
public $timestamps = [ "created_at" ]; // enable only to created_at
Run Code Online (Sandbox Code Playgroud)
小智 12
我的解决方案
class CreatePostsTable extends Migration {
public function up() {
Schema::create('posts', function(Blueprint $table){
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
Run Code Online (Sandbox Code Playgroud)
这适合我
自 Laravel 5.*
模型:
// Disable updated_at (only created_at)
class Book extends Model
{
const UPDATED_AT = null;
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
移民:
Schema::create('books', function (Blueprint $table): void {
/* ... */
$table->timestampTz('created_at')->nullable();
});
Run Code Online (Sandbox Code Playgroud)
小智 5
我通过CURRENT_TIMESTAMP在我的数据库中为 column添加默认值来解决created_at。在我的模型中,我使用下面的代码
public $timestamps = false;
protected $dates = ['created_at'];
Run Code Online (Sandbox Code Playgroud)
我希望这种方法适用于所有版本的 Laravel。
| 归档时间: |
|
| 查看次数: |
32239 次 |
| 最近记录: |