2016-11-10 39 views
1

我通過請求一個Json對象。 我明確解析這個對象,以檢查它是否適合目標模型。Laravel,如何投擲對象到新的雄辯模型?

而不是按屬性分配屬性。有沒有一種快速的方法來填充傳入對象的模型?

+0

我喜歡所有答案我很困惑接受爲「TheAnswer」,因爲每個人都在添加一些有趣的內容。 :) – koalaok

+0

我想你必須等待某人把它總結成「答案」;)或者..自己寫! – Paul

回答

1

您應該將該對象轉換爲數組並使用fill($attributes)方法。

如方法名稱所示,它將填充提供的值的對象。請記住,它不會持續到數據庫,你必須在此之後觸發save()方法。
或者,如果您想要填寫並堅持一種方法 - 有create($attributes),其中運行fill($attributes)save()

1

只是通過一個轉換到數組作爲模型構造函數參數的對象

$model = new Model((array) $object); 

在內部使用這個方法fill(),所以你可能需要先進入的屬性添加到$fillable財產或首先創建模型,然後使用forceFill()

1

可以使用Laravel的Mass Assignment功能,

你的模型應該是這樣的:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class User extends Model 
{ 
    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = ['name', 'email', 'phone']; 
} 

和填充模型的過程是這樣的:

// This would be your received json data converted to array 
// use 'json_decode($json, true)' to convert json data to array 
$json_arr = [ 
    'name' => 'User Name', 
    'email' => '[email protected]', 
    'phone' => '9999999999' 
]; 
$user = App\User::create($json_arr); 

希望這有助於!

1

如果你有一個數組的數組,然後你可以使用hydrate()方法將其轉換爲指定的模型的集合:

$records = json_decode($apiResult, true); 

SomeModel::hydrate($records); 

如果你只是有一個單一的記錄,那麼你就可以只需將該陣列傳遞給模型的構造函數:

$model = new SomeModel($record);