I'm quite new in Lumen but I have to do this because i have final task about Laravel.
So, i do have these two tables, the users and userTypes table.
usertypes table
+-----------------------+
| userTypeId | typeName |
+-----------------------+
| 1 | admin |
| 2 | buyer |
| 3 | store |
+-----------------------+
users table
+----------------------------------+
| id | name | email | userTypeId |
+----------------------------------+
| 1 | john | e@e.com | 2 |
+----------------------------------+
Now, what i was hoping the output for is something like this:
{
"data" : {
"id" : 1,
"nama" : "john",
"email" : "e@e.com",
"usertypes" : {
"typesName" : "buyer"
}
}
}
I've tried hasMany() and hasOne() and more but the "userTypes" field still return []. Here's the model for both of that.
User.php
....
public function usertype() {
return $this->hasMany(UserTypes::class, 'userTypeId');
}
....
UserTypes.php
.....
public function User() {
return $this->belongsTo(User::class);
}
.....
And here's the UserController.php
...
public function user($id) {
$user = User::with(['usertype'])->findOrFail($id);
return response()->json(['data' => $user]);
}
...
Any way to fix this? I appreciated for anyone who willing to help me. Thank you 🙏🙏
So it appears that i'm not fully understand the meaning of the "third parameters" and thanks to someone in telegram group that helping me out, in the User model it should be:
return $this->hasOne(UserTypes::class, 'userTypeId', 'userTypeId');
and it works. Second parameter is the foreign key on the users table, third parameter is the primary column name in that userTypes table. Hope it clears the dumb newbie like me.