How to create a One-To-Many relationship in Laravel?
After we learned about the types of relationships within Laravel in the previous part. We discussed the first type of these relationships, which is the One-To-One relationship.
Today we continue the series we started learning about Laravel Eloquent Relationships.
We are talking about the second type, which is called One-To-Many or hasMany.
How to create a One-To-Many relationship in Laravel?#
The One-To-Many relationship is one of the most important types of relationships inside Laravel Eloquent. We also learned in the previous lesson that it is the connection of a row from the first table to more than one row from the second table.
And as a continuation of the practical application (content management system), which we started in the previous lesson. We create a One-To-One relationship between the user and the personal profile.
Today we are going to create One-To-Many relationship between user and post. Each user can own one or more publications.
php artisan make:model Post -m
领英推荐
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->foreignId('user_id')->constrained();
$table->timestamps();
});
protected $fillable = [
'user_id',
'title',
'body',
];
php artisan migrate
public function posts() {
return $this->hasMany(Post::class);
}
Let’s learn how hasMany works
$this->hasMany(Post::class,
'user_id' // foreignKey By Default Parent Model + Promary Key
'id' // localKey => Primary Key In Parent Table By Default is Id
);
public function user() {
return $this->belongsTo(User::class);
}
We have explained belongsTo in this part of the previous article and we are explaining the One-To-One relationship.