我在帖子页面和标签表之间有变体关系。
Posts
id
othercolumn
Pages
id
othercolumn
tags
id
othercolumn
tagable_id
tagable_type
示例:我想同时将帖子添加到帖子表并将标签添加到标签表
DB::transaction(function(){
$post = new Post;
$post->othercolumn = Input::get('something');
$tags = new Tag;
$tag->othercolumn = Input::get('something');
// here function to store post and tag
if( //post or tag not created )
{
throw new \Exception('Failed to create post or tag');
}
});
如果我使用$ post-> tagable()-> save($ tag)之类的函数保存变形关系。将显示错误tagable_id不能为空。
答案 0 :(得分:0)
您不能同时存储模型,但是如果未保存第二个模型,则可以删除第一个模型:
DB::transaction(function(){
$post = new Post;
$post->othercolumn = Input::get('something');
$tag = new Tag;
$tag->othercolumn = Input::get('something');
if(!$post->save() || !$tag->save())
{
throw new \Exception('Failed to create post or tag');
}
});