Laravel中的填充方法不起作用?

mar*_*nes 13 php laravel

我正在学习如何使用Laravel框架,但我在填写模型时遇到了麻烦.这是我的代码:

型号Event:

<?php
class Event extends Eloquent {
  //Some functions not used yet
}
Run Code Online (Sandbox Code Playgroud)

这是控制器中的代码:

$event = new Event();
$event->fill(array('foo', 'bar'));
print_r($event->attributes);
Run Code Online (Sandbox Code Playgroud)

那么,为什么print_r显示一个空数组呢?

The*_*pha 31

属性是一个受保护的财产.使用$ obj-> getAttributes()方法.

其实.首先,你应该从改变模型名称Event到别的东西,Laravel有一个Facade班的Illuminate\Support\Facades\Event所以它可能是一个问题.

关于该fill方法,您应该将关联数组传递给fill方法,如:

$obj = new MyModel;
$obj->fill(array('fieldname1' => 'value', 'fieldname2' => 'value'));
Run Code Online (Sandbox Code Playgroud)

还要确保在具有允许填充的属性名称中声明了protected $fillable(检查质量分配)属性Model.初始化时,您也可以执行相同的操作Model:

$properties = array('fieldname1' => 'value', 'fieldname2' => 'value');
$obj = new ModelName($properties);
Run Code Online (Sandbox Code Playgroud)

最后,致电:

// Instead of attributes
dd($obj->getAttributes());
Run Code Online (Sandbox Code Playgroud)

因为attributes是受保护的财产.


小智 12

还要确保在模型类中定义了$ fillable属性.例如,在新的重命名模型中:

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['field1', 'field2'];
Run Code Online (Sandbox Code Playgroud)

如果您没有在模型上定义$ fillable或$ guarded,fill()将不会设置任何值.这是为了防止模型进行质量分配.请参阅Laravel Eloquent文档中的"质量分配":http://laravel.com/docs/5.1/eloquent .

填充属性时,请确保使用关联数组:

$event->fill(array('field1' => 'val1', 'field2' => 'val2'));
Run Code Online (Sandbox Code Playgroud)

调试和检查所有值的有用方法:

//This will var_dump the variable's data and exit the function so no other code is executed
dd($event);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!