dongnanbi4942 2016-03-17 00:08
浏览 48
已采纳

在Laravel中保存多态关系

I currently have a polymorphic relationship between phone numbers and contacts or organizations. I am using a morphMap to change the name of the parent relationship namespaced model to either contact or organization respectively.

Currently when I want to create a new phone number for an organization or contact I pass two URL parameters, parent_id=$record_id and parent_type=contact or organization. Then in my phone number controller I have the following which is super ugly:

    if ($request->parent_type == 'organization')
    {
        $parent_record = Organization::find($request->parent_id);
    }
    elseif ($request->parent_type == 'contact')
    {
        $parent_record = Contact::find($request->parent_id);
    }

    if ($parent_record)
    {
        $parent_record->phone_numbers()->save($phone_number);
        return redirect()->route($request->parent_type . '.show', ['id' => $request->parent_id])->with('notify', 'Phone number added!');
    }

I know that there has to be a better way for doing this since on every create or store method I duplicate this code. I just don't know how to make this better.

  • 写回答

1条回答 默认 最新

  • drfqfuhej48511519 2016-03-17 00:15
    关注
    $type = ucfirst($request->parent_type);
    if (in_array($type, $allowedTypes) {
        $parent_record = $type::find($request->parent_id);
    }
    

    You can use the scope resolution operator to invoke static method from a class, when the last one is represented by string.

    The catches here are two:

    1. The user can input a classname, you might not want to execute find(). Maybe a whitelist is needed
    2. The class is not part of this namespace - you need to use full qualified classname
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题