簡體   English   中英

使用Eloquent / Laravel 5.x通用創建模型/數據庫條目

[英]Generic creation of Model / DB entry with Eloquent / Laravel 5.x

我正在嘗試構建一個非常通用的函數,當id值為空或找不到時(以我為例),該函數可以接收模型名稱,id和值數組以更新現有模型或創建新模型

我遇到的問題是我找不到像通常那樣創建通用模型的正確方法: $mymodel = new Mymodel();

這是功能的相關部分。 它不起作用,我已經在Illuminate\\Database文件夾中挖掘了代碼

// lets get the model and then we update and save
$model = DB::table($request->input("model")."s")->where('id',$request->input("id"))->first();

if(!$model){
   $model = DB::table($request->input("model")."s")->new();
}

 // This part is not tested yet, but this part should set all the 
 // values from an Array of JSON objects, I will get that part to work
 foreach(json_decode($request->input("values")) as $value){
     $model->attributes[$value->name] = $value->value;
 } 

有誰知道我如何以最簡單的方式完成此任務? 我真的不想在一個單獨的函數中注冊我擁有的所有模型,並在那里創建它。 如果可能的話,我想讓它保持超通用。

您可以按照以下步驟進行操作,但請確保驗證和清理用戶輸入。

$modelClass = "App\\{$request->input('model')}";
$model = new $modelClass;

受到@joelrosenthal的回答的啟發,這里是完整的工作代碼,希望對您有所幫助:我將我的模型放在子文件夾中。

$modelClass = "\App\\".ucwords($request->input("model"));
if(!class_exists($modelClass)){
    $modelClass = "\App\\WFEModels\\".ucwords($request->input("model"));
}
// lets get the model and then we update and save
$model = $modelClass::where('id', $request->input("id"))->first();
// create new Instance if not found
if(!$model){
  $model = new $modelClass();
}
// fill values
foreach($request->input("values") as $value){
    $model[$value['name']] = $value['value'];
}
// save model
$model->save();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM