我有以下模型类
class MyModel extends Model {
public $some_variable; // I don't want to store this in the database
protected $fillable = ['column1', 'column2'];
在控制器中:
$model = MyModel::find(2);
$model->some_variable = "some value"; // Dynamically calculated each time
return response()->json($model);
响应包含MyModel
中的所有列,但不包含$some_variable
。为什么会发生这种情况?类变量默认是瞬态的吗?
答案 0 :(得分:0)
模型的数据在内部保存在$attributes
数组中,因此您可能希望在将数据转换为JSON之前将其放在那里:
...
$model->some_variable = ...;
return response()->json($model);
答案 1 :(得分:0)
因为您已在模型上定义了#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
int main ()
{
Display* d = XOpenDisplay(0);
XEvent ev;
Atom windowprop;
Atom actualType;
int format;
unsigned long numItems, bytesAfter;
unsigned char *data = NULL;
Atom netwmstate = XInternAtom(d, "_NET_WM_STATE", True);
Atom netwmstatefullscreen = XInternAtom (d, "_NET_WM_STATE_FULLSCREEN", True);
Window focus;
int revert_to = RevertToParent;
int result;
XSelectInput (d, RootWindow(d, DefaultScreen(d)), SubstructureNotifyMask);
while (1)
{
XNextEvent(d, &ev);
XGetInputFocus(d, &focus, &revert_to);
result = XGetWindowProperty(d,
focus,
netwmstate,
0L,
(~0L),
False,
AnyPropertyType,
&actualType,
&format,
&numItems,
&bytesAfter,
&data);
if (result == Success && data){
windowprop = ((Atom *)data)[0];
if (windowprop==netwmstatefullscreen){
system("xfconf-query -c xfwm4 -p /general/use_compositing -s false");
printf("Disabled compositing\n");
}
else {
system("xfconf-query -c xfwm4 -p /general/use_compositing -s true");
printf("enabled compositing\n");
}
}
}
}
,所以它不会显示在数组/ json输出中。 array / json输出仅包括表数据(存储在$some_variable
属性中)和加载的关系数据。
如果要显示此字段,可以覆盖模型上的$attributes
方法,也可以创建一个访问器方法并将其添加到toArray()
属性。
覆盖$appends
:
toArray()
使用访问者和class MyModel extends Model
{
public $some_variable;
public function toArray()
{
$data = parent::toArray();
$data['some_variable'] = $this->some_variable;
return $data;
}
}
:
$appends
您可以阅读accessors here。您可以阅读appending data to json here。