如何在laravel 8惯性中通过模型访问关系



我在用户表和区域表之间有一对多的关系,当我返回配置文件数据时,我从用户表中获得area_id,我需要使用模型获得区域名称。是否有一种方法,以获得区域名称在配置文件视图?我试着在show中调用模型函数。

User.php

public function area()
{
return $this->belongsTo(Area::class);
}

Area.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>

您需要手动加载您想要显示的所有关系。不像在Blade中,你不能仅仅访问与$user->area的关系,因为$user不是一个雄辩的实例,而是你作为JSON返回到你的Vue实例。

从控制器调用$user->load('area')。这将使您可以使用area

Controller.php:

$doctors = User::with('area')->paginate(5);

Vuefile.js

{{user.area.name}}

我有同样的问题,但最后我发现了另一个技巧,我在模型中定义了另一个方法,并添加了一个属性

在你的情况下:试试这个:Area.php

class Area extends Model
{ ....
$appends = ['users'];
public function users()
{
return $this->hasMany(User::class);
}

// define a methode getUsersAttribute()
public function getUsersAttribute(){
return $this->users()->get();
}

最新更新