我正在使用Vue.js,Vue Router,Axios和Laravel构建SPA。我的用户表中有一个外键,用于标识用户的“位置”。我正在尝试使用用户表中的外键从位置表中提取location_name。控制台显示该位置为空。
用户模型中的关系
<?php
public function location()
{
return $this->belongsTo('App\location','location');
}
位置模型中的关系
<?php
public function User()
{
return $this->hasMany('App\User');
}
控制器
<?php
public function show($id){
$User = User::with('location')->find($id);
return response()->json($User);
}
脚本
export default {
data: function() {
return {
tech:[]
}
},
mounted() {
axios.get('/tech/' + this.$route.params.id).then(response=>this.tech=response.data);
}
}
查看
<input type="text" v-model="tech.location.location_name">
routes.js
let routes = [
{
path:'/',
component:require('./views/dashboard/dashboard')
},
{
path:'/locations',
component:require('./views/locations/locations')
},
{
path:'/allLocations',
component:require('./views/locations/allLocations')
},
{
path:'/inActiveLocations',
component:require('./views/locations/inActiveLocations')
}
,
{
path:'/newLocation',
component:require('./views/locations/newLocation')
}
,
{
path:'/location/:id',
component:require('./views/locations/location')
}
,
{
path:'/editLocation/:id',
component:require('./views/locations/editLocation')
}
,
{
path:'/techs',
component:require('./views/techs/techs')
}
,
{
path:'/createTech',
component:require('./views/techs/createTech')
},
{
path:'/tech/:id',
component:require('./views/techs/tech')
}
web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
/* Locations*/
Route::post('/location','locationController@store');
Route::get('/locations','locationController@index');
Route::get('/inActiveLocations','locationController@inActiveLocations');
Route::get('/allLocations','locationController@allLocations');
Route::get('/location/{id}','locationController@show');
Route::get('/editLocation/{id}','locationController@edit');
Route::patch('/updateLocation/{id}','locationController@update');
/*Users*/
Route::get('/techs','techController@index');
Route::post('/tech','techController@store');
Route::get('/tech/{id}','techController@show');
答案 0 :(得分:-1)
您将需要对代码进行一些更改。您正在尝试检索属性而不是关系。要获取位置,您需要进行以下更改。
public function show($id){
$User = User::find($id);
$response = $User;
$response['location'] = $User->location;
return response()->json($response);
}