问题
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
}
}
]
I'd like to return it as:
"data": value,
"post":
{
"data": value,
"user": {
"data": value
}
}
What's the best way to go about it?
回答1:
Create a hasOne
association on your model that defines the scope you'd like.
public function activePost()
{
return $this->hasOne(Post::class)->active()->available();
]
Then call with('activePost.user')
to load that single, active and available post with it's associated user.
回答2:
As long as your relationship is a hasMany
, hasManyThrough
, belongsToMany
, morphMany
, morphedByMany
relationship (I think that's all of them), eager loading will always return an array since the primary use of the with
method is for adding clauses to a relationship.
Quoted from best answer on the laracasts forums: https://www.laracasts.com/discuss/channels/eloquent/first-and-take-do-not-work-correctly-in-eager-load-laravel?page=0)
@Dwight's answer is the right approach.
来源:https://stackoverflow.com/questions/48410201/return-object-using-with-in-laravel-eloquent