我试图用Vue.JS和Laravel构建一个页面应用程序。 我想展示最新的主题。
TopicController:
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"
等。我知道我可以加入用户表,但这不是一个额外的json?如何构建自定义json?提前谢谢,抱歉我的英语不好;)
答案 0 :(得分:3)
$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);
答案 1 :(得分:0)
请试试这个
Topic::select('id', 'title', 'author.author_name as author_id')
->join("author",'author.id','=','topic.author_id')
->orderBy('created_at', 'desc')
->limit(10)
->get();