我正在学习如何使用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
会显示一个空数组呢?
发布于 2015-08-26 17:00:38
还要确保在您的模型类中定义了$fillable
属性。例如,在新的重命名模型中:
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['field1', 'field2'];
如果您的模型中没有定义$fillable
或$guarded
,fill()
将不会设置任何值。这是为了防止对模型进行批量分配。请参阅Laravel Eloquent docs: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);
希望这能有所帮助!
发布于 2014-06-19 17:44:08
在fill中使用键/值数组:
举个例子:
$book->fill(array(
'title' => 'A title',
'author' => 'An author'
));
发布于 2018-06-09 03:32:35
在你的模型中,你需要有protected $fillable = ['foo','bar']
;
然后您可以执行以下操作:
$event = new Event(array('foo' => "foo", "bar" => "bar"));
$event->save(); // Save to database and return back the event
dd($event);
数组密钥需要在$fillable
上,因为Laravel将有效地调用:
foreach ($array as $key => $value){
$event->$key = $value;
}
或者,您可以直接写入列名:
$event = new Event();
$event->foo = "foo";
$event->bar = "bar";
$event->save();
dd($event);
https://stackoverflow.com/questions/24303003
复制相似问题