【问题标题】:Laravel Polymorphic Relation store data at same timeLaravel 多态关系同时存储数据
【发布时间】: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


【解决方案1】:

你不能同时存储到模型,但是如果第二个没有保存,你可以删除第一个模型:

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');
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2015-02-15
    • 2018-11-08
    • 2021-05-31
    • 2021-08-29
    • 2014-12-30
    • 2015-12-07
    相关资源
    最近更新 更多