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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂