我在模型中建立了hasOne关系,并且在驱动程序控制器中执行以下查询后,它可以正常工作:
$drivers = Driver::with('vehicleInfo')->first()->toArray();
驱动器型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Driver extends Model
{
// from_location_id
public function vehicleInfo()
{
return $this->hasOne('App\Vehicle','id','vehicle_id');
}
}
但是,当我尝试在Laravel Auth生成的AuthController中使用相同的代码时,这给了我未定义关系的错误。
我已将模型包含在AuthController中。如下:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Carbon\Carbon;
use App\User;
use App\Role;
use App\Driver;
class AuthController extends Controller
{
public function login(Request $request)
{
$request->validate([
'mobile' => 'required|string',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['mobile', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
// print_r($user);
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$user_details = User::find($user->id);
if($user_details->actual_user_id>0){
// find driver details
// var_dump(Driver::with('vehicleInfo'));
$driver_details = Driver::with('vehicleInfo')->first()->toArray();
// var_dump($driver_details);
}else{
$driver_details = "";
}
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
'user_details'=>$user_details->toArray(),
'driver_details'=>$driver_details
]);
}
}
我的关系是公开的。
请帮助。