|2||Creating model & migration|
|3||Configuration of migartion file|
|4||Creating user data|
|5||Creating relations in model|
|6||Condition based relationship|
In our old school we majorly uses query builder like join ( inner join , left join ) to find a relation of single id in many table or using RDBMS(Relationship based Database Management System) its very important to when you are working on a project where single id has relations in many tables . For eg - we have a table users and a table name user_contacts , to get user corressponding address we may use join or left join but we have different option which is known as ORM Relaionship . ORM Relationship are good practice when you are working on a big project as to make the length of the code short and easy to understand.
So starting with creating model and migration hit the below command in the terminal and it will create a model and corresponding migration in your laravel application
command for model: Copy
This wil crreate a model app/Models/UserContacts and a migration file now paste the following code in migration file database/migrations/xxxx_create_user_contacts_table.php . As you can see in the below code we are using $table->unsignedBigInteger('user_id)->nullable() and in the bottom of the code $table->foreign('user_id')->refrence('id')->on('users')->onDelete('cascade') as this will create a foreign key refrence of users table id in user_contacts table with the name user_id as shown below.
code for migration: Copy
Now hit php artisan migrate to create a migration in database
command for migrate: Copy
After that we will create some dummy data in UserContacts . In any controller create some dummy data and call this function as we are creating data in user_contacts table as example , this function createDeveloper() will create a new user and id of this user will save in user_contacts making user_id as foreign key. Copy
Now we have many address that belongs to single user (user_id = 109).
As seen user_id 109 hasMay addresses in user_contacts table now we call this addresss by relationship.
For BelongsToMany Relationship you may consider Belongs To Many Relationship in Laravel 10
In app/Models/User.php we are creating hasOne(one to one) relation and hasMany(one to many) relation , if you are having different foreign key then you may define your foreign key under the relationship class as shown in manyContact() function .
code for model:Copy
so basically we have two functions here singleContact = hasOne and manyContact=hasMany relationship .
Now call this function in any controller using with statement as shown in below code we are fetching data from both the functions to show the difference between OneToOne and OneToMany in OneToOne it only sends single array whereas in OneToMany it sends all the contacts under many_contact array
code for controller: Copy
Result we get .
If you want add any condition like orderBy clause or any clause or whrere condition do it in this way