Laravel中的填充方法不起作用? [英] Fill method in Laravel not working?
问题描述
我正在学习如何使用Laravel框架,但是在填充模型时遇到了麻烦.这是我的代码:
I am learning how to use Laravel framework but I am having troubles with filling a Model. Here is my code:
模型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
显示一个空数组?
So, why the print_r
is displaying an empty array?
推荐答案
属性是受保护的财产.使用 $ obj-> getAttributes()方法.
The attributes is a protected property. Use $obj->getAttributes() method.
实际上.首先,您应该将模型名称从Event
更改为其他名称,Laravel
的Facade
类为Illuminate\Support\Facades\Event
,因此可能是一个问题.
Actually. at first you should change the model name from Event
to something else, Laravel
has a Facade
class as Illuminate\Support\Facades\Event
so it could be a problem.
关于fill
方法,您应该将关联数组传递给fill
方法,例如:
Regarding the fill
method, you should pass an associative array to fill
method like:
$obj = new MyModel;
$obj->fill(array('fieldname1' => 'value', 'fieldname2' => 'value'));
还要确保您声明了protected $fillable
(检查质量分配)属性在Model
中使用允许填充的属性名称.初始化Model
时,您也可以做同样的事情:
Also make sure you have a protected $fillable
(check mass assignment) property declared in your Model
with property names that are allowed to be filled. You may also do the same thing when initializing the Model
:
$properties = array('fieldname1' => 'value', 'fieldname2' => 'value');
$obj = new ModelName($properties);
最后,致电:
// Instead of attributes
dd($obj->getAttributes());
因为attributes
是受保护的属性.
这篇关于Laravel中的填充方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!