[英]How to get rid of unnecessary field (relation) from collection of Eloquent models?
I've fetched bunch of models ::with('something')
.我已经获取了一堆模型::with('something')
。 I have a collection of these models with eager loaded collection.我收集了这些带有急切加载集合的模型。 I've performed some operation on this collection and now I don't need this relation in my final JSON output.我已经对这个集合执行了一些操作,现在我不需要这个关系在我的最终 JSON output 中。
How can I get rid of it?我怎样才能摆脱它?
return Foo::with(['something'])->get(['id', 'content', 'target']);
When I return JSON response I get 4 columns (id, content, target and something).当我返回 JSON 响应时,我得到 4 列(id、内容、目标等)。 I want 3 columns.我想要 3 列。 How to get rid of something
before the final return of response?如何在最终返回响应之前摆脱something
?
Which method should I use?我应该使用哪种方法?
#relations: array:1 [
"something" => Illuminate\Database\Eloquent\Collection {#1225
EDIT:编辑:
->each(function (Foo $foo) {
unset($foo['something']);
})
->values();
This does the job but it doesn't look nice.这可以完成工作,但看起来不太好。 Is there a better way?有没有更好的办法?
You can map
( each
accessor) the content and hide
the relation:您可以map
( each
访问者)内容并hide
关系:
return Foo::with(['something'])
->get(['id', 'content', 'target'])
->each->makeHidden('something');
Your method might work, but IMO it's not the best option, because if you (for example, in the future) will change the code, and manipulate the relation after the unset
, then you might encounter some troubles, where instead hide
is just "hiding" the relation (you can do the same with attributes) from the serialization您的方法可能有效,但 IMO 这不是最佳选择,因为如果您(例如,将来)将更改代码,并在unset
之后操纵关系,那么您可能会遇到一些麻烦,而hide
只是“从序列化中隐藏“关系(你可以对属性做同样的事情)
You can find the documentation here您可以在此处找到文档
If it's not clear why and how ->each->...
works, check here如果不清楚->each->...
为什么以及如何工作,请查看 此处
You can use the transform
method of laravel collections.可以使用laravel collections的transform
方法。
return Foo::with(['something'])->get()->transform(function($item, $key){
return $item->only(['id', 'content', 'target']);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.