Laravel Form 存储多态关系的最佳方式

我有一个笔记模型。其中具有多态性“值得注意”。理想情况下任何人都可以使用的方法。可能最多可以使用 5 种不同的模型,例如客户、员工、用户等。


我正在寻找尽可能动态地根据这些内容创建注释的最佳解决方案。


目前,我正在路线中添加查询字符串。 IE。查看客户时,会出现“添加注释”选项按钮像这样:


route('note.create', ['customer_id' => $customer->id])

在我的表单中,我正在检查任何查询字符串并将它们添加到有效的发布请求(在 VueJS 中)。


然后在我的控制器中,我正在检查每个可能的查询字符串,即:


if($request->has('individual_id'))

{

   $individual = Individual::findOrFail($request->individual_id_id);

   // store against individual

   // return note

   }elseif($request->has('customer_id'))

   {

      $customer = Customer::findOrFail($request->customer_id);

      // store against the customer

      // return note

   }

我很确定这不是最好的方法。但是,我暂时想不出其他办法。


我相信其他人过去也遇到过这种情况!


弑天下
浏览 83回答 4
4回答

红糖糍粑

为了优化您的代码,不要在代码中添加太多if else ,例如,如果您有大量的多态关系,那么您是否会添加大量<我=2>?您愿意吗?它将快速增加您的代码库。 请尝试以下提示。if else当调用后端时进行映射,例如$identifier_map = [1,2,3,4];// 1&nbsp; for Customer// 2&nbsp; for Staff// 3&nbsp; for Users&nbsp;// 4&nbsp; for Individual等等然后使用 noteable_id 和 调用笔记控制器noteable_identifierroute('note.create', ['noteable_id' => $id, 'noteable_identifier' => $identifier_map[0]])然后在控制器的后端你可以做类似的事情if($request->has('noteable_id') && $request->has('noteable_identifier')){&nbsp; &nbsp; $noteables = [ 'Customers', 'Staff', 'Users','Individual']; // mapper for models,add more models.&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $noteable_model = app('App\\'.$noteables[$request->noteable_identifier]);&nbsp; &nbsp; &nbsp; &nbsp; $noteable_model::findOrFail($request->noteable_id);}因此,通过这些代码行,您可以处理大量的多态关系。

月关宝盒

不确定最好的方法,但我有与你类似的情况,这是我使用的代码。我的表单操作看起来像这样action="{{ route('notes.store', ['model' => 'Customer', 'id' => $customer->id]) }}"action="{{ route('notes.store', ['model' => 'User', 'id' => $user->id]) }}"ETC..我的控制器看起来是这样的public function store(Request $request){&nbsp; &nbsp; // Build up the model string&nbsp; &nbsp; $model = '\App\Models\\'.$request->model;&nbsp; &nbsp; // Get the requester id&nbsp; &nbsp; $id = $request->id;&nbsp; &nbsp; if ($id) {&nbsp; &nbsp; &nbsp; &nbsp; // get the parent&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $parent = $model::find($id);&nbsp; &nbsp; &nbsp; &nbsp; // validate the data and create the note&nbsp; &nbsp; &nbsp; &nbsp; $parent->notes()->create($this->validatedData());&nbsp; &nbsp; &nbsp; &nbsp; // redirect back to the requester&nbsp; &nbsp; &nbsp; &nbsp; return Redirect::back()->withErrors(['msg', 'message']);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // validate the data and create the note without parent association&nbsp; &nbsp; &nbsp; &nbsp; Note::create($this->validatedData());&nbsp; &nbsp; &nbsp; &nbsp; // Redirect to index view&nbsp; &nbsp; &nbsp; &nbsp; return redirect()->route('notes.index');&nbsp; &nbsp; }}protected function validatedData(){&nbsp; &nbsp; // validate form fields&nbsp; &nbsp; return request()->validate([&nbsp; &nbsp; &nbsp; &nbsp; 'name' => 'required|string',&nbsp; &nbsp; &nbsp; &nbsp; 'body' => 'required|min:3',&nbsp; &nbsp; ]);}

人到中年有点甜

/**&nbsp;* Store a newly created resource in storage.&nbsp;*&nbsp;* @param&nbsp; \Illuminate\Http\Requests\NoteStoreRequest&nbsp; $request&nbsp;* @return \Illuminate\Http\Response&nbsp;*/public function store(NoteStoreRequest $request) {&nbsp; &nbsp; // REF: NoteStoreRequest does the validation&nbsp; &nbsp; // TODO: Customize this suffix on your own&nbsp; &nbsp; $suffix = '_id';&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Resolve model class name.&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @param&nbsp; string&nbsp; $name&nbsp; &nbsp; &nbsp;* @return string&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; function modelNameResolver(string $name) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO: Customize this function on your own&nbsp; &nbsp; &nbsp; &nbsp; return 'App\\Models\\'.Str::ucfirst($name);&nbsp; &nbsp; }&nbsp; &nbsp; foreach ($request->all() as $key => $value) {&nbsp; &nbsp; &nbsp; &nbsp; if (Str::endsWith($key, $suffix)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $class = modelNameResolver(Str::beforeLast($key, $suffix));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $noteable = $class::findOrFail($value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $noteable->notes()->create($request->validated());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // TODO: Customize this exception response&nbsp; &nbsp; throw new InternalServerException;}

一只名叫tom的猫

据我了解,情况是:-您从创建表单提交 noteable_id-您想要删除 store 函数上的 if 语句。您可以通过从 create_form“noteable_type”发送请求中的另一个密钥来做到这一点。所以,你的商店路线将是route('note.store',['noteableClass'=>'App\User','id'=>$user->id])在 Notes 控制器上:public function store(Request $request){&nbsp; &nbsp; return Note::storeData($request->noteable_type,$request->id);}您的 Note 模型将如下所示:class Note extends Model{&nbsp; &nbsp; public function noteable()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->morphTo();&nbsp; &nbsp; }&nbsp; &nbsp; public static function storeData($noteableClass,$id){&nbsp; &nbsp; &nbsp; &nbsp; $noteableObject = $noteableClass::find($id);&nbsp; &nbsp; &nbsp; &nbsp; $noteableObject->notes()->create([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'note' => 'test note'&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; return $noteableObject->notes;&nbsp; &nbsp; }}这适用于商店中的 get 方法。对于帖子,可以提交表单。
打开App,查看更多内容
随时随地看视频慕课网APP