should the id always be the foreign key ?

Discussion for various published PHP frameworks, including Zend Framework, CodeIgniter, Kohana, CakePHP, Yii, Symfony, and others.

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

should the id always be the foreign key ?

Post by gautamz07 »

I have a table Admin(should have actully named it articles :P ) with the following fields:

Code: Select all

ID
title 
keywords
blog_content
tag
filePath
slug
created_at
updated_at
And Then i have the Tags table with the following feilds:

Code: Select all

Id
tag
Now i want to create a hasMany relationship between the Admin and the Tags table. How do i do this ? I mean which field in the Admin table will be the foreign key ? i believe usually the foreign key is always the ID field , even the docs show the same: HERE --> https://laravel.com/docs/5.4/migrations ... onstraints , or should can i make the tag feild in the Admin table as the foreign key to the ID in the Tags table ?

I still have a scrambled brain about this issue and hence i taught it would be best to ask here, can somebody please give me a bit more clarity on this topic ?

Thank you.
Gautam.
User avatar
Celauran
Moderator
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: should the id always be the foreign key ?

Post by Celauran »

Why do you have a tag field in the admin table? (and yes, you should change that table name)

If you're setting up a has and belongs to many (ie. an article can have many tags, a tag can belong to many articles), then you'll want a pivot table for both IDs. See https://laravel.com/docs/5.4/eloquent-r ... ny-to-many
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Re: should the id always be the foreign key ?

Post by gautamz07 »

OK Thanks celaurian ! :)
Post Reply