laravel relationship (one to one , one-to-many )
ReportAn Eloquent relationship is a very important feature in Laravel that allows you to relate the tables in a very easy format.
One to one relationship
One to one relationship provides the one-to-one relationship between the columns of different tables. For example, every user is associated with a single post or maybe multiple posts, but in this relationship, we will retrieve the single post of a user. To define a relationship, we need first to define the post() method in User model. In the post() method, we need to implement the hasOne() method that returns the result.
public function post(){
return $this->hasOne('App\Post');
}
Inverse Relation
Inverse relation means the inverse of the one-to-one relationship. In the above, we have retrieved the post belonging to a particular user. Now, we retrieve the user information based on the post.
public function user() {
return $this->belongsTo('App\User');
}
One-to-many relationship
Laravel also provides a one-to-many relationship.
public function posts() {
return $this->hasMany('App\Post','user_id');
}
Thread Reply