dongnanbi4942
2016-03-17 00:08 阅读 38
已采纳

在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 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
    点赞 评论 复制链接分享

相关推荐