簡體   English   中英

Laravel 5陣列,模型中帶有鍵保存

[英]Laravel 5 Array with key save in model

有陣列有關鍵和價值 鍵名稱是相同的數據庫列名稱。

索引中的鍵總數大於50。

  • 所以, 不可能像往常一樣保存數據

     $user = new User; $user->name = 'John'; .......... ....... .......so on $user->save(); 

樣本數組:

Array
(
    [name] => 'Amit',
    [age] => 25,
    [field1] => 'val1',
    ....
  [field33] => 'how'    ,
....
   [field54] => 'sumit'     
)

現在,我的問題是如何使用最簡單的流程在模型中保存數據

信息:

  • 使用laravel 5

嘗試:

$Plan=new Plans;
 $Plan->fill( $array);
 $Plan->save();

注意: 我知道填充不起作用,因為它沒有在該模型的可填充變量中定義

Eloquent模型封裝了對象的屬性。 因此,您只能通過set$model->attribute )或fill(array $attributes)方法更改/設置它們。 質量分配屬性的所有Eloquent方法都使用方法fill()

因此,有兩種方法可以在數據庫中插入帶有數組的基於Eloquent的新模型,一種使用fill()方法,另一種使用dons't。

方法1:批量分配

添加屬性protected $fillable = [ 'column_a', 'column_b', .. ]; 到你的模型。 然后你可以像這樣使用質量分配。

$Plan = new Plans;
$Plan->fill( $array );
$Plan->save();

或者您可以使用:

$plan = Plans::create( $array );

方法2:QueryBuilder :: insert(數組)

如果在creatingcreated時沒有注冊任何boot方法(DB不會觸發這些),那么您也可以使用QueryBuilder在數據庫中插入行。

// insert one plan
DB::table('plans')->insert([ $array ]);
$plan = Plans::find( DB::getPdo()->lastInsertId() );

// insert multiple plans in one query
$plans = [ $plan_a_arr, $plan_b_arr, .. ];
DB::table('plans')->insert( $plans );

我不明白為什么你不想在你的模型的$fillable屬性中定義數據庫列/數組鍵,因為它只是一次性任務,然后你就可以這樣做:

$plan = Plans::create( $array );

另一種方法是,如果你擁有一個關聯數組中的所有數據,其中的鍵與數據庫表中的列匹配,那么就是使用foreach循環:

$plan = new Plans;
foreach( $array as $key => $value )
{
    $plan->$key = $value;
}
$plan->save();

暫無
暫無

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

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