在Laravel Eloquent中使用with()返回对象 [英] Return object using with() in Laravel Eloquent
本文介绍了在Laravel Eloquent中使用with()返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我得到的数据如下:
Currently I get data like so:
->with(['posts' => function ($query) {
$query->active()->available()->limit(1)->with('user');
}])
,它以预期的对象数组形式返回用户数据.因为我正在使用一个限制,并且只需要一个结果,所以我想将其作为常规对象返回,所以不要:
and it returns the user data as an array of objects which is expected. Because I am using a limit and will only ever need one result, I'd like to return it as a regular object, so instead of:
"data": value,
"posts": [
{
"data": value,
"user": {
"data": value
}
}
]
我想将其返回为:
"data": value,
"post":
{
"data": value,
"user": {
"data": value
}
}
最好的方法是什么?
推荐答案
在模型上创建一个hasOne
关联,以定义所需的范围.
Create a hasOne
association on your model that defines the scope you'd like.
public function activePost()
{
return $this->hasOne(Post::class)->active()->available();
]
然后调用with('activePost.user')
,以为其关联用户加载该单个,活动和可用的帖子.
Then call with('activePost.user')
to load that single, active and available post with it's associated user.
这篇关于在Laravel Eloquent中使用with()返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文