为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
弑天下 2023-12-15 17:06:57
我有一个笔记模型。其中具有多态性“值得注意”。理想情况下任何人都可以使用的方法。可能最多可以使用 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   }我很确定这不是最好的方法。但是,我暂时想不出其他办法。我相信其他人过去也遇到过这种情况!
查看完整描述

4 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

为了优化您的代码,不要在代码中添加太多if else ,例如,如果您有大量的多态关系,那么您是否会添加大量<我=2>?您愿意吗?它将快速增加您的代码库。 请尝试以下提示。if else


当调用后端时进行映射,例如


$identifier_map = [1,2,3,4];


// 1  for Customer

// 2  for Staff

// 3  for Users 

// 4  for Individual


等等


然后使用 noteable_id 和 调用笔记控制器noteable_identifier


route('note.create', ['noteable_id' => $id, 'noteable_identifier' => $identifier_map[0]])


然后在控制器的后端你可以做类似的事情


if($request->has('noteable_id') && $request->has('noteable_identifier'))

{

    $noteables = [ 'Customers', 'Staff', 'Users','Individual']; // mapper for models,add more models.

       

        $noteable_model = app('App\\'.$noteables[$request->noteable_identifier]);

        $noteable_model::findOrFail($request->noteable_id);


}

因此,通过这些代码行,您可以处理大量的多态关系。


查看完整回答
反对 回复 2023-12-15
?
月关宝盒

TA贡献1772条经验 获得超5个赞

不确定最好的方法,但我有与你类似的情况,这是我使用的代码。


我的表单操作看起来像这样


action="{{ route('notes.store', ['model' => 'Customer', 'id' => $customer->id]) }}"

action="{{ route('notes.store', ['model' => 'User', 'id' => $user->id]) }}"

ETC..


我的控制器看起来是这样的


public function store(Request $request)

{

    // Build up the model string

    $model = '\App\Models\\'.$request->model;

    // Get the requester id

    $id = $request->id;


    if ($id) {

        // get the parent 

        $parent = $model::find($id);

        // validate the data and create the note

        $parent->notes()->create($this->validatedData());

        // redirect back to the requester

        return Redirect::back()->withErrors(['msg', 'message']);

    } else {

        // validate the data and create the note without parent association

        Note::create($this->validatedData());

        // Redirect to index view

        return redirect()->route('notes.index');

    }

}


protected function validatedData()

{

    // validate form fields

    return request()->validate([

        'name' => 'required|string',

        'body' => 'required|min:3',

    ]);

}


查看完整回答
反对 回复 2023-12-15
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

/**

 * Store a newly created resource in storage.

 *

 * @param  \Illuminate\Http\Requests\NoteStoreRequest  $request

 * @return \Illuminate\Http\Response

 */

public function store(NoteStoreRequest $request) {

    // REF: NoteStoreRequest does the validation


    // TODO: Customize this suffix on your own

    $suffix = '_id';


    /**

     * Resolve model class name.

     * 

     * @param  string  $name

     * @return string

     */

    function modelNameResolver(string $name) {

        // TODO: Customize this function on your own

        return 'App\\Models\\'.Str::ucfirst($name);

    }


    foreach ($request->all() as $key => $value) {

        if (Str::endsWith($key, $suffix)) {

            $class = modelNameResolver(Str::beforeLast($key, $suffix));

            $noteable = $class::findOrFail($value);

            return $noteable->notes()->create($request->validated());

        }

    }


    // TODO: Customize this exception response

    throw new InternalServerException;

}


查看完整回答
反对 回复 2023-12-15
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

据我了解,情况是:

-您从创建表单提交 noteable_id

-您想要删除 store 函数上的 if 语句。


您可以通过从 create_form“noteable_type”发送请求中的另一个密钥来做到这一点。所以,你的商店路线将是


route('note.store',['noteableClass'=>'App\User','id'=>$user->id])

在 Notes 控制器上:


public function store(Request $request)

{

    return Note::storeData($request->noteable_type,$request->id);

}

您的 Note 模型将如下所示:


class Note extends Model

{

    public function noteable()

    {

        return $this->morphTo();

    }

    public static function storeData($noteableClass,$id){

        $noteableObject = $noteableClass::find($id);

        $noteableObject->notes()->create([

            'note' => 'test note'

        ]);

        return $noteableObject->notes;

    }

}

这适用于商店中的 get 方法。对于帖子,可以提交表单。


查看完整回答
反对 回复 2023-12-15
  • 4 回答
  • 0 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信