我正在学习如何使用Laravel框架,但我在填写模型时遇到了麻烦。这是我的代码:
模型Event
:
<?php
class Event extends Eloquent {
//Some functions not used yet
}
以下是控制器中的代码:
$event = new Event();
$event->fill(array('foo', 'bar'));
print_r($event->attributes);
那么,为什么print_r
显示一个空数组?
答案 0 :(得分:27)
属性是受保护的属性。使用 $ obj-&gt; getAttributes()方法。
实际上。首先,您应该将模型名称从Event
更改为其他内容,Laravel
将Facade
类更改为Illuminate\Support\Facades\Event
,这样可能会出现问题。
关于fill
方法,您应该将关联数组传递给fill
方法,如:
$obj = new MyModel;
$obj->fill(array('fieldname1' => 'value', 'fieldname2' => 'value'));
还要确保在protected $fillable
中声明了Model
(check mass assignment)属性,并且允许填充属性名称。初始化Model
:
$properties = array('fieldname1' => 'value', 'fieldname2' => 'value');
$obj = new ModelName($properties);
最后,请致电:
// Instead of attributes
dd($obj->getAttributes());
因为attributes
是受保护的属性。
答案 1 :(得分:10)
还要确保在模型类中定义了$ fillable属性。例如,在新的重命名模型中:
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['field1', 'field2'];
如果您没有在模型上定义$ fillable或$ guarded,则fill()不会设置任何值。这是为了防止模型进行质量分配。参见&#34; Mass Assignment&#34;在Laravel Eloquent文档上:http://laravel.com/docs/5.1/eloquent。
填充属性时,请确保使用关联数组:
$event->fill(array('field1' => 'val1', 'field2' => 'val2'));
调试和检查所有值的有用方法:
//This will var_dump the variable's data and exit the function so no other code is executed
dd($event);
希望这有帮助!
答案 2 :(得分:2)
在填充中使用键/值数组:
一个例子:
$book->fill(array(
'title' => 'A title',
'author' => 'An author'
));
答案 3 :(得分:0)
在您的模型中,您需要 val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)
;
然后你可以这样做:
protected $fillable = ['foo','bar']
数组键需要在$event = new Event(array('foo' => "foo", "bar" => "bar"));
$event->save(); // Save to database and return back the event
dd($event);
上,因为Laravel会有效地调用:
$fillable
或者,您可以直接写入列名:
foreach ($array as $key => $value){
$event->$key = $value;
}
答案 4 :(得分:-1)
在Laravel 5.x中,
当你想创建一个新行时:
$model = App\ModelName::create($arr);
当你想要更新现有的行时:
$model = App\ModelName::find($id);
$model->fill($arr);
所有可填充属性都存在于模型变量$fillable
中。