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.

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

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启