To define category has many posts we have to define this relationship in our Category model. Open your terminal again and run following command to create two models as show below:Ībove command will create models in app/Models directory.ĭefine One-to-Many relation in Laravel Model Now, that we have our table migrations ready we would create models based on above table structure. Generate Eloquent Models Using Command Line: id () $table -> string ( 'title' ) // define foreign key $table -> foreignId ( 'category_id' ) -> constrained ( 'categories' ) -> onUpdate ( 'cascade' ) -> onDelete ( 'cascade' ) $table -> timestamps () }) } /** We also have to add foreign key constraint here. You can add more columns as you need for demo purpose we choose to use minimal columns. Posts table migration would look like following: Schema :: dropIfExists ( 'categories' ) } } id () $table -> string ( 'title' ) $table -> string ( 'description' ) $table -> timestamps () }) } /** Php artisan make:migration create_posts_tableĪlright, above command will generate two migrations in database/migrations folder:Ĭategories table migration would look like following: Php artisan make:migration create_categories_table It is important you follow order in order to generate migrations due to the fact that we would have to add foreign key constraint in post table. ![]() Go to your laravel root folder and open up your terminal and run following commands: In order to create this type of relationship in Laravel we would have to create two migrations for our categories and posts table. ![]() How to define One to Many relationship in Laravel? You can now say that you can find many posts that belongs to single category therefore this type of relationship is called one-to-many where one category has many posts. you can find all posts that belongs to Laravel category Imagine you have posts table and categories tableĬategory may have many posts i.e. When one table refers to many rows in another table that is called a one-to-many relationship. What is One to Many relationship in laravel?Ī one-to-many relationship is a very basic type of database relationship. ![]() Laravel Eloquent: One To Many Relationship.Laravel Eloquent: One To Many Relationship
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |