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 .
So starting with creating model and migration 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 . Copy
Here we define our user_id as foreign key with refrence to users table. Now hit php artisan migrate in terminal Copy
After that we will create some dummy data in UserContacts . In any controller create some dummy data and call this function . Copy
Now we have many address that belongs to single user .
As seen user_id 109 hasMay addresses in user_contacts table now we call this addresss by relationship.
In app/Models/User.php paste the following code in User model Copy
so basically we have two functions here singleContact = hasOne and manyContact=hasMany relationship .
If you have different foriegn key in table just define it there along with auto-increment key.
Now call this function in any controller Copy
Call thiis function by any controller..Result we get .
if you want add any condition like orderBy clause or any clause or whrere condition do it in this way Copy
For BelongsToMany Relationship you may consider developer-corner.vm-services.tech/developer-corner/post/1662920799/make+user-roles+by+using+eloquent+method+with+pivot-table+in+laravel