Laravel:返回包含其他数据的更新模型

我成功更新了数据透视表中的数据。我现在正在尝试返回更新的模型-包括刚刚更新的数据透视表数据。

我能够返回模型,但不确定如何从那里获取数据。

这是我的控制人:

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);
            }
        },},
gangan123321 回答:Laravel:返回包含其他数据的更新模型

仅在加载了对应关系时才加载数据透视表数据。否则,将不执行任何查询来触摸数据透视表。使用默认的# Route Model Binding,仅检索模型。

您将需要显式执行关系驱动的查找。

// load the role using the relationship
$role_with_pivot = $user->roles()->where('id',$role->id)->first();

// in some circumstances,it may be necessary to use the full table name
// $role_with_pivot = $user->roles()->where('roles.id',$role->id)->first();

return response()->json(['role' => $role_with_pivot],200); 

然后您应该能够在响应中访问数据透视。

let active = response.data.role.pivot.active;
本文链接:https://www.f2er.com/3155763.html

大家都在问