2017-04-08 17 views
1

Q1。我有一個將屬性轉換爲集合的Eloquent模型。 在此屬性上調用集合的方法不會影響模型值。例如:如預期雄辯鑄造屬性收藏意外行爲

$var = collect(); 
$var->put('ip', '127.0.0.1'); 
var_dump($var); 

輸出:put()

當使用集合,IAM能夠做到這一點

object(Illuminate\Support\Collection)[191] protected 'items' => array (size=1) 'ip' => string '127.0.0.1' (length=4)

但是,當我在洋洋灑灑模型與鑄造屬性使用,這不能按預期工作

$user = App\User::create(['email'=>'Name', 'email'=>'[email protected]', 'password'=>bcrypt('1234')]); 
$user->properties = collect(); 
$user->properties->put('ip', '127.0.0.1'); 
var_dump($user->properties); 

object(Illuminate\Support\Collection)[201] protected 'items' => array (size=0) empty

這不填充字段。 我認爲創建了另一個集合,所以要按預期工作,我必須將這個新集合分配給我的字段。

像這樣: $user->properties = $user->properties->put('ip', '127.0.0.1');

Q2。是否有合適的方法來默認初始化字段集合(如果字段爲空,則創建一個空集合),而不必每次都手動調用$user->properties = collect();


user.php的

class User extends Authenticatable 
{ 
    protected $casts = [ 
     'properties' => 'collection', 
    ]; 
    ... 
} 

遷移文件

Schema::table('users', function($table) { 
    $table->text('properties')->nullable(); 
}); 

回答

0

Q1:鑄造到集合的屬性具有吸氣返回,各時間,一個new BaseCollection它構建在屬性的值上。

前面已經假定,吸氣返回另一收集實例,並在它的每一個直接改不會改變屬性的價值,而是新創建的集合對象。

正如您所指出的,設置集合鑄造屬性的唯一方法是將它自己的原始值與新的屬性合併。

所以不是put()你必須使用:

$user->properties = $user->properties->put('ip', '127.0.0.1'); 
// or 
$user->properties = $user->properties ->merge(['ip'=>'127.0.0.1']) 

Q2:我們認爲,該數據庫表示是文本;所以恕我直言,在遷移初始化模式的正確方法是給它一個默認空JSON,即:

$table->text('properties')->default('{}'); 

但是這個作品只對沒有設置屬性字段創建的模型後檢索。

對於新創建型號我的建議是通過默認void array,即:

App\User::create([ 
    'name'=>'Name', 
    'email'=>'[email protected]', 
    'password'=>bcrypt('1234'), 
    'properties' => [] 
]); 
0

除了dparoli優秀的答案,還可以通過Laravel的引導添加默認值方法,該方法可在每個模型上使用。

類似下面的例如代碼

protected static function boot() 
    { 
     parent::boot(); //because we want the parent boot to be run as well 
     static::creating(function($model){ 
     $model->propertyName = 'propertyValue'; 
     }); 
    } 

你可以,如果你用這種方法打就好爲好。

+0

這真是一個很好的解決方案 – dparoli