Last active
February 2, 2023 08:15
-
-
Save ahmadshuami/6b2e65b4af32134d3abd83c796243a06 to your computer and use it in GitHub Desktop.
Laravel Relationship
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## hasOne (user has one address), (address own by one user) ## | |
-------------------------------------------------------------- | |
- User Model | |
protected $fillable = [ | |
'id', | |
'name' | |
]; | |
- Address Model | |
protected $fillable = [ | |
'id', | |
'address_name', | |
'user_id' | |
]; | |
- in User Model | |
public function address() | |
{ | |
return $this->hasOne(Address::class,'user_id','id); | |
// user_id => FK in Address Model | |
// id => Local key / PK of user in User Model | |
} | |
- in Address Model | |
public function user() | |
{ | |
return $this->belongsTo(User::class,'user_id','id'); | |
// user_id => FK in Address Model | |
// id => Local key / PK of user in User Model | |
} | |
## hasMany (user has many addresses), (addresses own by user) ## | |
---------------------------------------------------------------- | |
- in User Model | |
public function addresses() | |
{ | |
return $this->hasMany(Address::class,'user_id','id); | |
// user_id => FK in Address Model | |
// id => Local key / PK of user in User Model | |
} | |
- in Address Model | |
public function user() | |
{ | |
return $this->belongsTo(User::class,'user_id','id'); | |
// user_id => FK in Address Model | |
// id => Local key / PK of user in User Model | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment