【发布时间】:2019-11-06 23:18:51
【问题描述】:
我已成功更新数据透视表中的数据。我现在正尝试返回更新后的模型 - 包括刚刚更新的数据透视数据。
我能够返回模型,但不确定如何从那里获取数据透视数据。
这是我的控制器:
public function update(Request $request, Role $role)
$user->roles()->updateExistingPivot($attributes['id'], $attributes); // 200 status
...
return response()->json(['role' => $role], 200);
// have also tried this - and does return the value, but would like the whole object if possible.
$active = $user->roles->find($attributes['id'])->pivot->active;
}
这是我的User 模型:
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_user', 'user_id')
->withPivot('active') // this is the column I am updating
->withTimestamps();
}
以上一切正常。我的数据正在更新,我的数据透视表中的时间戳也是如此。
我(认为)我遇到的问题是我返回的 $role 与传入的相同。我正在使用 vue 组件来呈现结果,所以我想使用实际的数据从我的数据库中返回。
即使我使用查询查找Role,我也只是将模型取回;不包括我想阅读的数据透视列。
我正在检查我的 vue 组件中的响应,如下所示:
console.log('response.data', response.data);
response.data {
role:
created_at: "..."
title: "foo"
...
}
上面渲染了相同的模型对象(没有枢轴列)。如何将我的 active 数据透视列附加到响应数据?感谢您的建议!
解决方案
感谢 matticustard 的帮助。这正是我需要指向正确方向的推动。这是我的代码的样子,希望对其他人有所帮助。
控制器
$public function update(Request $request, Role $role)
{
$attributes = request()->validate([
'active' => 'required',
'id' => 'required',
]);
$user = auth()->user();
$user->roles()->updateExistingPivot($attributes['id'], $attributes);
// Return the role using the relationship.
$role_with_pivot = $user->roles()->where('role_id', $attributes['id'])->first();
return response()->json(['role' => $role_with_pivot], 200);
}
更新我的数据库后,以上内容将作为响应返回:
role:
created_at: "..."
icon: "..."
id: 1
pivot:
active: true
role_id: 1
user_id: 1
...
title: "foo"
...
vue 组件
<template>
<div class="role" :class="{'active': active}" @click="handleClick($event, role)">
<div v-if="role.icon" class="role-icon">
<i :class="role.icon"></i>
</div>
<div class="role-title">
{{ role.title }}
</div>
</div>
</template>
...
data() {
return {
active: this.role.pivot.active,
}
},
...
methods: {
async handleClick(event, role) {
try {
let response = await axios.patch(`/my-path/${role.id}`, {
active: !this.active,
id: role.id,
});
if (response.status === 200) {
console.log('response.data', response.data);
this.active = response.data.role.pivot.active;
console.log('active: ', this.active);
} else {
console.error('Error: could not update role. ', response);
}
} catch (error) {
console.error('Error: sending patch request. ', error);
}
},
},
【问题讨论】: