【问题标题】:Make Trait protected attributes accessible to Eloquent in Laravel 4.2在 Laravel 4.2 中让 Eloquent 可以访问 Trait 保护的属性
【发布时间】: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();

namedescription 保存得很好,虽然我有 timesAskedfactornextTime 的列,但当我 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


    【解决方案1】:

    Eloquent 会将值存储在内部属性数组中。这是实际写入数据库的内容。如果它们已经作为模型上的数据成员存在,它将不会将值写入属性数组。查看__set and __get 魔术方法以及它们在Illuminate/Database/Eloquent/Model 中的使用方式

    长话短说,从模型中删除受保护的数据成员。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2017-07-10
      • 2014-09-13
      • 1970-01-01
      • 2016-07-08
      • 2020-01-20
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多