1

我有 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);
}
4

2 回答 2

0

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

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

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

于 2017-01-25T19:09:26.497 回答
0

使用急切加载

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

此外,如果用户具有一个角色和一个分支,则关系应该belongsTo()belongsToMany()

return $this->belongsTo('App\User');
于 2017-01-25T19:11:17.630 回答