【问题标题】:Laravel query join as extra jsonLaravel 查询连接为额外的 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?在此先感谢,并为我的英语不好感到抱歉;)

【问题讨论】:

    标签: php mysql json laravel vue.js


    【解决方案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);
    

    【讨论】:

    • 正是我需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多