Return object using with() in Laravel Eloquent

℡╲_俬逩灬. 提交于 2019-12-11 15:22:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!