Interview question
What is the difference between hasOne, hasMany, belongsTo, and belongsToMany relationships? hasOne, hasMany, belongsTo और belongsToMany relationships में क्या अंतर है?
Answer
| Relationship | Meaning | Foreign key location |
|---|---|---|
| hasOne | One model owns one related model | On the related table |
| hasMany | One model owns many related models | On the related table |
| belongsTo | Inverse of hasOne/hasMany | On the current table |
| belongsToMany | Many-to-many relationship | Pivot table |
class User extends Model {
public function posts() {
return $this->hasMany(Post::class);
}
}
class Post extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}
class User extends Model {
public function roles() {
return $this->belongsToMany(Role::class);
}
}| Relationship | अर्थ | Foreign key कहाँ |
|---|---|---|
| hasOne | एक model, एक related model का owner | Related table पर |
| hasMany | एक model, कई related models का owner | Related table पर |
| belongsTo | hasOne/hasMany का उल्टा | Current table पर |
| belongsToMany | Many-to-many | Pivot table |
class User extends Model {
public function posts() {
return $this->hasMany(Post::class);
}
}Was this answer clear?