亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超3個贊

據我了解,情況是:

-您從創建表單提交 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 關注
  • 267 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號