显示具有 2 个相关表记录的用户

Displaying users with 2 related tables records

我有 3 个模型:

用户、角色和分支。

它们是这样相关的:

注入用户模型:

class User extends Model
{
    // Define fields to be fillable
    protected $fillable = [
                            'firstname', 
                            'lastname',
                            'telephone',
                            'address',
                            'password',
                            'code',
                            'status',
                            'branches_id',
                            'roles_id'
                        ];

    /**
     * Get the role record associated with the user.
     */
    public function role()
    {
        return $this->hasOne('App\Role');
    }

    /**
     * Get the branch record associated with the user.
     */
    public function branch()
    {
        return $this->hasOne('App\Branch');
    }
}

榜样:

class Role extends Model
{
    // Define fields to be fillable
    protected $fillable = ['description'];

    /**
     * Get the user that owns the role.
     */
    public function user()
    {
        return $this->belongsToMany('App\User');
    }
}

对于分支模型:

class Branch extends Model
{
    // Define fields to be fillable
    protected $fillable = ['description', 'location'];

    /**
     * Get the user that owns the branch.
     */
    public function user()
    {
        return $this->belongsToMany('App\User');
    }
}

我知道如果我使用 Blade 来列出用户的角色,我可以这样做:$user->role()

但我正在尝试将 angular 2 用于前端,将 laravel 5.3 用于后端。

我的问题是如何检索用户以及角色和分支

这是我的 UserController 中的索引操作:

public function index()
{
    // Get all users, along with roles and branches
    $users = User::all();

    // Send the response
    return response()->json([
            'users' => $users
        ], 200);
}

您可以为此使用 with() 方法,例如

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

有关详细信息,请参阅 https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

使用eager loading:

$users = User::with('role', 'branch')->get();

此外,如果用户有一个角色和一个分支,关系应该是 belongsTo() 而不是 belongsToMany():

return $this->belongsTo('App\User');