Laravel-如何导出具有关系的两个表

时间:2019-06-03 08:51:03

标签: laravel maatwebsite-excel

我想使用Laravel 5.8导出到Excel

  

“ maatwebsite / excel”:“ ^ 3.1”

型号:

  1. UserReward(user_rewards)
  2. 用户(用户)

我有此密码

        $points = DB::table("user_rewards")
         ->select("user_rewards.user_id", "users.username","user_rewards.user_id", DB::raw("SUM(user_rewards.points) as no_game"))
        ->join("users","users.id","=","user_rewards.user_id")
         ->groupBy("users.id","users.username","user_rewards.user_id")
         ->orderByRaw('SUM(user_rewards.points) DESC');

但是想要将其转换为类似的内容

导出

class GamesExport implements FromQuery, WithHeadings, ShouldAutoSize, WithEvents
{  
    use Exportable;
    /**
    * @return \Illuminate\Support\Collection
    */
    public function query()
    {
        return User::query()->select('name', 'username', 'created_at');
        ...
    }
}

如何使用导出关系的两个表

  

query()->选择

或转换

  

DB :: raw上至

     

query()->选择

如上所示

1 个答案:

答案 0 :(得分:1)

您可以尝试使用with来加载关系。

https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

这样,结果将是这样的: User::with('userRewards')(假设userRewards是关系的名称)