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();
});
这真是一个很好的解决方案 – dparoli