dshw124502 2017-05-29 11:08
浏览 106
已采纳

Laravel选择对象作为属性

I'd like to know if it is possible to do a left join in a query and if it exists instead of having all the columns in the same "level" make the joined table go as a property (This without any relationships)

For example

$users = user::leftJoin("posts","users.id","=","posts.user_id")->get();

Instead of returning every field together,

["id"/*This actually gets messed up if select doesn't choose wich to use*/,
  "name",
  "age",
  /*Now post fields*/
  "tile",
  "date_posted"
  ...
]

and having it return

["id",
  "name",
  "age",
  "post"=>[
    "id",
    "tile",
    "date_posted"
    ...
   ]
]

Edit: If possible to avoid loops for obvious reasons... I know it is possible and in last resort will use them but not using loops would help out alot

  • 写回答

1条回答 默认 最新

  • dpzyd8865 2017-05-29 12:10
    关注

    You're using eloquent for the users table. Why not use relationships? It does exactly what you want. Create a new Post model. Then add the following relationship to your User model.

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
    

    You can now fetch the users with post like so

    $users = User::with('posts')->get();
    

    The result is exactly what you want. Also I've used User in my example, where as you've used user. The result would contain the posts object as posts instead of post as you've shown in the example, you can change this property name by changing the relationship method name. I've used these since they're the right convention.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效