我一直在使用->("with"(在查询类似这样的模型时用于关系…
return Model::
where('set_id', $request->set)
->without('set')
->with('user:id,first_name,last_name,profile_photo')
->get();
这对一段关系很有效:
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
但是,对属性做同样的操作呢?
public function getPermissionsAttribute(){
$permissions = $this->permissions;
$new = [];
foreach($permissions as $p){
$new[$p->permission] = true;
}
return json_encode($new);
}
在拉拉威尔有办法做到这一点吗?目前我收到以下错误。。。
AppModelsUser::permissions must return a relationship instance. (View: C:UsersNickPhpstormProjectslaravel-vueresourcesviewsindex.blade.php)
我确实有:
public $appends = [
'full_name',
'profile_photo_thumb',
'permissions'
......... etc ............
];
但是,列表越来越长,我向前端发送的数据基本上没有使用,因此导致加载时间更长
您可以在运行时附加访问器,通过在Eloquent Collection:上调用append
来帮助您决定要在响应中序列化的数据
return $collection->append('attribute');
或者对于多个,您可以传递一个数组:
return $collection->append(['attribute1', 'attribute2']);
Laravel 8.x Docs-Eloquent-序列化-将值附加到JSON-在运行时附加append
尝试通过选择类似的函数来获得它
return Model::where('set_id', $request->set)->with(['user' => function ($query) {
$query->select('id','first_name','last_name','profile_photo');
}])