What is the difference between BelongsTo And HasOne in Laravel

后端 未结 5 457
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 16:19

Can any body tell me what is the main difference between
the BelongsTo and HasOne relationship in eloquent.

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 17:09

    The main difference is which side of the relation holds relationship's foreign key. The model that calls $this->belongsTo() is the owned model in one-to-one and many-to-one relationships and holds the key of the owning model.

    Example one-to-one relationship:

    class User extends Model {
      public function car() {
        // user has at maximum one car, 
        // so $user->car will return a single model
        return $this->hasOne('Car');
      }
    }
    
    class Car extends Model {
      public function owner() {
        // cars table has owner_id field that stores id of related user model
        return $this->belongsTo('User'); 
      }
    }
    

    Example one-to-many relationship:

    class User extends Model {
      public function phoneNumbers() {
        // user can have multiple phone numbers, 
        // so $user->phoneNumbers will return a collection of models
        return $this->hasMany('PhoneNumber');
      }
    }
    
    class PhoneNumber extends Model {
      public function owner() {
        // phone_numbers table has owner_id field that stores id of related user model
        return $this->belongsTo('User'); 
      }
    }
    

提交回复
热议问题