我在Laravel做项目。我使用过laravel的雄辩模型。我想用时间戳值将记录插入数据库。
以下是我的模型'Provider.php'
{
protected $primaryKey = 'provider_id';
protected $table = 'provider';
protected $fillable = [
'organization_name',
'email',
'website',
'mobile',
'landline',
'password',
'added_by'
];
public function cities(){
return $this->belongsToMany('App\City','provider_city','provider_id','city_id');
}
}
'City.php'
{
protected $primaryKey = 'city_id';
protected $table = 'city';
protected $fillable = ['state_id','name'];
}
我的控制器方法如下,
{
$city_selection = $request->input('city_selection');
$provider = Provider::findOrFail($provider_id);
foreach ($city_selection as $city) {
$provider->cities()->attach($city['city_id']);
}
}
其中city_selection如下所示,
"city_selection":
[
{
"city_id": 1,
"name": "Pune"
},
{
"city_id": 3,
"name": "Bangalore"
}
]
之后当我尝试插入记录时,所有文件,即provider_id和city_id字段都正确地进入数据库,但唯一的问题是created_at和updated_at字段仍为空。
我用过timpstamps();在创建迁移文件时。我不知道出了什么问题。
有什么建议吗?
答案 0 :(得分:0)
您需要添加日期变更器。
https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
class Provider extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
}
答案 1 :(得分:0)
在架构中添加时间戳
$table->timestamps();
您的架构看起来像这样
Schema::create('city', function(Blueprint $table){
$table->increments('id');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('state');
$table->string('name', 100);
$table->timestamps();
});
答案 2 :(得分:0)
在表架构中添加以下列。
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
插入记录时 created_at
列将存储值,并且当此记录中的任何更改(行中的任何更新)时updated_at
将保持更新。
更新
使用以下代码在新迁移中更新
public function up()
{
Schema::table('table_name', function($table) {
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
});
}