User::all 显示关系项

User::all show relationship items

我Laravel 5.5我正在返回这样的用户信息...

$users = User::all();

return Response::json(array(
    'error' => false,
    'response' => $users,
));

我有一个属于多个类别的关系设置,还想显示每个用户所属的所有类别。

有人举个例子吗?

使用with()方法为每个用户加载类别:

$users = User::with('categories')->get();

如果您不需要加载 categories table 中的所有列,请在 with() closure 中使用 select()。此外,由于您使用的是 Laravel 5.5,因此您可以使用 Resource 类 来格式化 JSON.