我是新手使用Traits,在我的雄辩模型中保存我的特质的受保护属性时遇到了麻烦:
这是我的路线模型:
namespace App\Models;
use Eloquent;
class Route extends Eloquent {
use CardTrait {
CardTrait::__construct as __CardConstruct;
}
public $timestamps = false;
protected $table = 'routes';
protected $primaryKey = 'id';
protected $visible = [
'name',
'description'
];
public function __construct(array $attributes = array())
{
$this->__CardConstruct($attributes);
}
//relationships follow
}
这是CardTrait的特点:
namespace App\Models;
trait CardTrait {
protected $timesAsked;
protected $factor;
protected $nextTime;
public function __construct($attributes = array(), $timesAsked = 0, $factor = 2.5, $nextTime = null)
{
parent::__construct($attributes);
if (is_null($nextTime)) $nextTime = \Carbon::now()->toDateTimeString();
$this->factor = $factor;
$this->nextTime = $nextTime;
$this->timesAsked = $timesAsked;
public function answer($difficulty)
{
if($difficulty < 3)
$this->timesAsked = 1;
}
//other methods follow
}
在我的控制器中,我可以使用:
$route = new Route();
$route->name = "New Name";
$route->description = "New Description";
$route->answer(5);
$route->save();
name
和description
保存得很好,虽然我有timesAsked
,factor
和nextTime
的列,当我dd($ route)时,我可以看到
protected 'timesAsked' => int 1
protected 'factor' => float 2.6
protected 'nextTime' => string '2015-04-15 21:36:53' (length=19)
所以我知道Trait的方法工作正常。
我的问题是如何使用Eloquent保存这些值,以便可以从数据库中存储和检索这些值?
提前致谢。
答案 0 :(得分:0)
Eloquent会将值存储在内部属性数组中。这是实际写入数据库的内容。如果它们已作为模型上的数据成员存在,它将不会将值写入属性数组。查看__set and __get魔术方法及其在Illuminate/Database/Eloquent/Model
中的使用方法长话短说,从模型中删除受保护的数据成员。