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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?