Reputation: 1480
I have a user table that consists of these columns:
| id | username | password | email | pants_size_id | shirt_size_id |
pants_size_id
and shirt_size_id
are filled with foreign tables id keys where I store a list of sizes for pants and shirts in different country specific measures, example of pants_size
table:
| id | UK_sizing | US_sizing | IT_sizing |
a single user will have only one pants and shirt size so the user table is filled with the ID of the corresponding rows in the size tables.
what kind of relationship does this imply between the user model and the pants and shirt sizing models?
Also how can I retrieve the data inside the foreign table column (example IT_sizing) when returning auth user return \Auth::user();
instead of the numeric size_id ?
In other words how can I retrieve say '32' (a pants size) instead of the pants_size_id
(let's say '1').
Upvotes: 2
Views: 79
Reputation: 964
Cato has the right answer, I can't exactly respond to it because of my rep but the logic in your other answer doesn't make sense from a relational standpoint.
Users don't belong to a size, instead, Users have a size.
To me it sounds like you mixed up the foreign and local key assignment it should be User->hasOne(pants_size).
In your model it would be the following, the explicitness of the keys isn't great, but if you have some weird thing laravel can't figure out this should work.
public function pants_size(){
return $this->hasOne('App\Pants_size','id','pants_size_id');
}
public function shirt_size(){
return $this->hasOne('App\Shirt_size','id','shirt_size_id');
}
To answer the other question of how to find the size (32), since you're dealing with three different measurements you have to have a where clause on the specific measurement the 32 represents, and get the id. If you specifically wanted the users you would call the eloquent query as so:
\Auth::User()->pants_size()->(..whatever measurement you want..)
Upvotes: 1
Reputation: 1480
this is how I made it work:
in USER model:
public function pants_size(){
return $this->belongsTo('App\Pants_size');
}
public function shirt_size(){
return $this->belongsTo('App\Shirt_size');
}
In Pants_size and Shirt_size Models:
public function user(){
return $this->hasMany('App\User');
}
That last one works also with hasOne.
The code I use to retrieve the data is:
public function index()
{
echo $user = User::find($id);
echo $pants = User::find($id)->pants_size->it_sizing;
echo $shirt = User::find($id)->shirt_size->it_sizing;
}
Upvotes: 0
Reputation: 3099
Create a function
establishing a hasOne
relationship for both pants_size
and shirt_size
in the user
model. Be sure to set the foreign key
and local key
correctly if you don't want Laravel to assume default keys (see here for details).
Once the functions
are created, you will be able to obtain data about the user's size information like so: App\Model\User::find(123)->pants_size->UK_sizing
. (This example is for a user with ID of 123).
Upvotes: 0