laravel Eloquent 同步和 created_at/updated_at
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26059691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent sync and created_at/updated_at
提问by Marcin Nabia?ek
I have the following code:
我有以下代码:
$entry->save();
$categories = [];
$categories[Input::get('main_category')] = ['main' => 1];
for ($i=1; $i<=4 ; ++$i) {
$input = Input::get('category_'.$i);
if ($input != '') {
$categories[$input] = ['main' => 0];
}
}
$entry->categories()->sync($categories);
$inTags = explode(',', trim( Input::get('tags'), ','));
$tags = [];
foreach ($inTags as $tag) {
$tag = trim($tag);
if ($tag == '') {
continue;
}
$fTag = Tag::firstOrCreate(array('name' => $tag));
$tags[$fTag->id] = ['entry_id' => $entry->id];
}
$entry->tags()->sync($tags);
In above code I create entry ($entry->save()
is here just enough to understand it, earlier code is not important), then save to which categories this entry belongs to (using pivot table) and do the same with tags (but for tags if tag doesn't exist I create one).
在上面的代码中,我创建了条目($entry->save()
这里只是足以理解它,早期的代码并不重要),然后保存该条目所属的类别(使用数据透视表)并对标签执行相同的操作(但对于标签,如果标签不t 存在我创建一个)。
However in both pivot tables created_at
field is left default (0000-00-00 00:00:00
) after inserting data (probably the same will be with updated_at
but I haven't tested it ).
但是,在插入数据后,两个数据透视表中的created_at
字段都保留为默认值 ( 0000-00-00 00:00:00
)(可能与此相同,updated_at
但我尚未对其进行测试)。
Do I need somehow activate filing timestamps automatically or need I fill them manually on my own (but probably it will mean much more coding and no using sync
)?
我需要以某种方式自动激活归档时间戳还是需要我自己手动填写它们(但这可能意味着更多的编码而不是使用sync
)?
回答by Jarek Tkaczyk
In order to handle pivot timestamps when you sync/attach belongsToMany
relation, you need to include withTimestamps()
on the relation definition:
为了在同步/附加belongsToMany
关系时处理枢轴时间戳,您需要withTimestamps()
在关系定义中包含:
// some model
public function someRelation()
{
return $this->belongsToMany('RelatedModel')->withTimestamps();
}
Then every sync
/attach
/updateExistingPivot
will set/update the timestamps on your pivot table.
然后每sync
/ attach
/updateExistingPivot
将设置/更新您的数据透视表的时间戳。