Laravel 查询连接为额外的 json
Posted
技术标签:
【中文标题】Laravel 查询连接为额外的 json【英文标题】:Laravel query join as extra json 【发布时间】:2018-04-22 12:30:33 【问题描述】:我正在尝试使用 Vue.JS 和 Laravel 构建单页应用程序。 我想展示最新的话题。
主题控制器:
public function index()
return response()->json( Topic::allTopics() );
主题:
public static function allTopics()
return Topic::select('id', 'title', 'author_id')
->orderBy('created_at', 'desc')
->limit(10)
->get();
通过这个我得到了这样的东西:
[
"id":322,"title":"mytitle..","author_id":"authorname",
"id":321,"title":"anothertitle..","author_id":"authorname.."
]
如何将作者设为额外的 json?喜欢
id: N,
title: "title",
author_id: 5
author_name: "Name",
author_avatar: "default.png"
等等。我知道我可以加入 users 表,但这不是额外的 json 吗?如何构建我的自定义 json?在此先感谢,并为我的英语不好感到抱歉;)
【问题讨论】:
【参考方案1】:请试试这个
Topic::select('id', 'title', 'author.author_name as author_id')
->join("author",'author.id','=','topic.author_id')
->orderBy('created_at', 'desc')
->limit(10)
->get();
【讨论】:
I know that I can join users table, but this don't be an extra json
:)【参考方案2】:
$result = Topic::select('id', 'title', 'author.author_name as author_id')
->join("author",'author.id','=','topic.author_id')
->orderBy('created_at', 'desc')
->limit(10)
->get();
$array = [];
foreach($result as $data)
$array[] = [
'id'=> $data->id,
'key_name2'=> $data->title,
......
];
return response()->json($array);
【讨论】:
正是我需要的。谢谢!以上是关于Laravel 查询连接为额外的 json的主要内容,如果未能解决你的问题,请参考以下文章
如何将左连接横向 SQL 查询转换为 Laravel Eloquent 查询?