我在用户表和区域表之间有一对多的关系,当我返回配置文件数据时,我从用户表中获取 area_id,我需要使用模型获取区域名称。 有没有办法在个人资料视图中获取区域名称? 我试图在 show.vue 中调用模型函数,但它不起作用。
用户.php
public function area()
{
return $this->belongsTo(Area::class);
}
区域.php
public function users()
{
return $this->hasMany(User::class);
}
show.vue
<template>
<app-layout>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Profile
</h2>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Area :
</h2>
</template>
<div>
<div class="max-w-7xl mx-auto py-10 sm:px-6 lg:px-8">
<div v-if="$page.props.jetstream.canUpdateProfileInformation">
<update-profile-information-form :user="$page.props.user" />
<jet-section-border />
</div>
<div v-if="$page.props.jetstream.canUpdatePassword">
<update-password-form class="mt-10 sm:mt-0" />
<jet-section-border />
</div>
<div v-if="$page.props.jetstream.canManageTwoFactorAuthentication">
<two-factor-authentication-form class="mt-10 sm:mt-0" />
<jet-section-border />
</div>
<logout-other-browser-sessions-form :sessions="sessions" class="mt-10 sm:mt-0" />
<template v-if="$page.props.jetstream.hasAccountDeletionFeatures">
<jet-section-border />
<delete-user-form class="mt-10 sm:mt-0" />
</template>
</div>
</div>
</app-layout>
</template>
<script>
import AppLayout from '@/Layouts/AppLayout'
import DeleteUserForm from './DeleteUserForm'
import JetSectionBorder from '@/Jetstream/SectionBorder'
import LogoutOtherBrowserSessionsForm from './LogoutOtherBrowserSessionsForm'
import TwoFactorAuthenticationForm from './TwoFactorAuthenticationForm'
import UpdatePasswordForm from './UpdatePasswordForm'
import UpdateProfileInformationForm from './UpdateProfileInformationForm'
export default {
props: ['sessions'],
components: {
AppLayout,
DeleteUserForm,
JetSectionBorder,
LogoutOtherBrowserSessionsForm,
TwoFactorAuthenticationForm,
UpdatePasswordForm,
UpdateProfileInformationForm,
},
}
</script>
答案 0 :(得分:2)
您需要手动加载要显示的所有关系。与 Blade 不同,您不能只访问与 $user->area
的关系,因为 $user
不是 Eloquent 实例,而是您作为 JSON 返回到您的 Vue 实例的内容。
从您的控制器调用 $user->load('area')
。这将使您可以使用 area
。