简体   繁体   English

如何将 hasOne 关系数据从 laravel controller 传递到 Vue 前端

[英]How can I pass hasOne relationship data from laravel controller to Vue frontend

I am trying to make a blog like app using Laravel and Vue but got stuck at a point.我正在尝试使用 Laravel 和 Vue 制作一个类似应用程序的博客,但被卡住了。 While developing the admin panel, I wanted a "Assign role" feature there where the admin can assign a user with particular role like "Admin, Moderator or Author" For that, I defined a relationship in User model在开发管理面板时,我想要一个“分配角色”功能,管理员可以在其中分配具有特定角色的用户,例如“管理员、版主或作者”为此,我在用户 model 中定义了一个关系

public function role() {
    return $this->hasOne(Role::class);
}

Now in Vue, I want to display a table with all user names with their Roles besides them.现在在 Vue 中,我想显示一个表格,其中包含所有用户名及其角色。 For that, I sent a request to laravel server to fetch all data from Users table, the users table have the fields below为此,我向 laravel 服务器发送了一个请求,以从用户表中获取所有数据,用户表具有以下字段

id, name, role_id, email, password, created_at, updated_at id、名称、role_id、email、密码、created_at、updated_at

I have a relationship defined in the Role model aswell我在角色 model 中也定义了一个关系

public function Users() {
    return $this->hasMany(User::class);
}

Now when I fetch all users, I do现在,当我获取所有用户时,我会

$users = User::all();
return $users;

How can I get the Role name inside my table, from the data i sent above.如何从我上面发送的数据中获取表中的角色名称。 Right now, I am only getting the role_id that is 1,2 or 3 but I want the names of the roles.现在,我只得到 1,2 或 3 的 role_id,但我想要角色的名称。

Thanks in advance提前致谢

You need to change your relation.你需要改变你们的关系。

User Model用户 Model

public function role(){
   return $this->belongsTo(App\Role::class, 'role_id', 'id')
}

You can use the role relation and get the name from there.您可以使用角色关系并从那里获取名称。

// Eager load the relation
$users = User::with('role')->get();
return $users;

In your html.在您的 html 中。

$user->role->name;

I think one of your relationships is wrong for starters, should be我认为你的一段关系对于初学者来说是错误的,应该是

public function role() {
    return $this->belongsTo(Role::class);
}

To minimize database queries do this:要最小化数据库查询,请执行以下操作:

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

Now you can do something like现在你可以做类似的事情

$users->toJson()

if you want to pass all the data to a javascript.如果要将所有数据传递给 javascript。

Or you can do或者你可以做

@foreach($users as $user)
    {{ $user->role->name }}
@endforeach

The important thing is that the with statement loads all the relationships in advance and so only one database query is executed.重要的是with语句会预先加载所有关系,因此只执行一个数据库查询。

$users = User::all();
foreach($users as $user) {
    $user->role;
}
return $users;

Believe it or not, that's all you need to do to populate the relationship inside any generated JSON.信不信由你,这就是在任何生成的 JSON 中填充关系所需要做的一切。 You just have to call the "magic method"你只需要调用“魔术方法”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM