【发布时间】:2019-05-03 12:15:24
【问题描述】:
我正在使用 Vue.js、Vue Router、Axios 和 Laravel 构建一个 SPA。我的用户表中有一个外键来标识用户的“位置”。我正在尝试使用用户表中的外键从 Locations 表中提取 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');
【问题讨论】:
-
调试101:1)我没用过axios,但是你试过
console.logresponse.data变量吗?以 vue-resource 为例,数据将在response.body下。 2)控制台中是否有任何错误? 3)您确定关系正确并返回位置吗?也许类名/命名空间不正确? 4) 具有提供的 ID 的用户是否存在?该用户所属的位置是否存在?编辑:您确实检查了控制台,抱歉。 -
突出的是您的第一个关系使用
'App\location'作为类名,按照惯例,这不是类的名称。类名应遵循PascalCase表示法。为了更好的代码稳定性,请使用public function location() { return $this->belongsTo(Location::class); }。 -
请显示您的路线@TA
-
@saurabhkamble 我已经添加了路线。
标签: laravel vue.js eloquent axios vue-router