我在流明还很陌生,但我必须这样做,因为我要完成有关Laravel的任务。
所以,我确实有这两个表,users和userTypes表。
用户类型表
+-----------------------+
| userTypeId | typeName |
+-----------------------+
| 1 | admin |
| 2 | buyer |
| 3 | store |
+-----------------------+
用户表
+----------------------------------+
| id | name | email | userTypeId |
+----------------------------------+
| 1 | john | [email protected] | 2 |
+----------------------------------+
现在,我希望输出的是这样的:
{
"data" : {
"id" : 1,
"nama" : "john",
"email" : "[email protected]",
"usertypes" : {
"typesName" : "buyer"
}
}
}
我已经尝试过hasMany()和hasOne()等,但“ userTypes”字段仍返回[]。这是两者的模型。
User.php
....
public function usertype() {
return $this->hasMany(UserTypes::class, 'userTypeId');
}
....
UserTypes.php
.....
public function User() {
return $this->belongsTo(User::class);
}
.....
这是UserController.php
...
public function user($id) {
$user = User::with(['usertype'])->findOrFail($id);
return response()->json(['data' => $user]);
}
...
任何解决此问题的方法?我感谢任何愿意帮助我的人。谢谢🙏🙏
Its better to use find method you use route model binding. when you pass id
to method User $user auto find user from databse. now we have $user so we
call relation $user->usertype.
public function user(User $user) {
return response()->json(['data' => $user->usertype]);
}