【发布时间】:2019-07-16 07:54:01
【问题描述】:
我在帖子页面和标签表之间有变形关系。
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 不能为空。
【问题讨论】:
-
你不能这样做,因为你需要post id
-
那么我怎样才能获得帖子 ID?如果尝试使用 $post->id 获取帖子 id 但返回 null ...因为使用 db 事务...仍然可以使用该方法?
-
第一个创建帖子,第二个创建标签
-
如果先创建帖子,然后再创建标签....如何在未创建标签时删除帖子...如数据库事务...将回滚帖子
-
if (!$tags->save()) {$post->delete();}
标签: php database laravel polymorphism