Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 6 of 10 · Laravel Framework Fundamentals
Interview question

What is the difference between hasOne, hasMany, belongsTo, and belongsToMany relationships? hasOne, hasMany, belongsTo और belongsToMany relationships में क्या अंतर है?

Answer
RelationshipMeaningForeign key location
hasOneOne model owns one related modelOn the related table
hasManyOne model owns many related modelsOn the related table
belongsToInverse of hasOne/hasManyOn the current table
belongsToManyMany-to-many relationshipPivot 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 का ownerRelated table पर
hasManyएक model, कई related models का ownerRelated table पर
belongsTohasOne/hasMany का उल्टाCurrent table पर
belongsToManyMany-to-manyPivot table
class User extends Model {
    public function posts() {
        return $this->hasMany(Post::class);
    }
}

Was this answer clear?