【发布时间】:2015-06-20 16:36:02
【问题描述】:
我刚开始使用 Traits,在我的 eloquent 模型中保存我的 trait 的受保护属性时遇到了麻烦:
这是我的路线模型:
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 保存这些值,以便可以从数据库中存储和检索这些值?
提前致谢。
【问题讨论】:
标签: php laravel eloquent traits