class User extends Eloquent {
protected $table = 'my_users';
// The 'my_users' table does *not* provide this column.
protected $computedValue;
public function doSomething() {
// Anyway, for some reason, i need the property to exist in the model.
$this->computedValue = 'foo';
}
}
当我执行User::save()
时,会触发错误,因为Eloquent正在尝试insert into my_users (computedValue) values('foo')
实际上,在我触发保存之前,我没有设置属性。是否有另一种方式(除了监听保存事件以取消设置),例如
protected $discard = array('computedValue', 'anyOtherFieldNotToMap');
答案 0 :(得分:3)
您可以尝试将该成员变量设为默认值。
protected $computedValue = false;
参考Laravel论坛Setting transient properties on Eloquent models without saving to database?
似乎已经为海报工作了。
答案 1 :(得分:0)
我认为您可以通过将整个模型转换为数组然后访问所需的属性值来实现。
看一下本页的结尾
"将值附加到JSON" https://laravel.com/docs/5.1/eloquent-serialization