bashiro's avatar

RETRIEVING COLUMN VALUE NAME USING A FOREIGN ID COLUMN

Hello folks, Thanks for any help_ I have been working on student subjects register.Previously When registering a subject in the subject table, I had a column with the name subject_category, where I add subject category.It was easy to retrieve what category the subject belongs to.

Now,I have separated the subject_category and it is on a category table. I have created a foreign key subject_category_id on the subject table. The subject_category_id is the id of the subject category on the subject_Category Table.

Getting the subject category name from using the subject_category_id has been a challenge. I have this relationship in the subject model: public function subject_category_name(){ return $this->belongsTo(SubjectCategory::class, 'subject_category_id', 'id'); }

public function subjects(){
    return $this->hasMany(SchoolSubjects::class,  'id','subject_category_id');

 } 
 Any help ?
 
 Thanks
0 likes
5 replies
Shivamyadav's avatar

First thing you need to focus on Laravel will look for pivot table name based on the alphabet order ..

It will look for category_subject but you have created subject_category and in the relationship there you need to tell the Laravel that which table and which column manually..

Your relationship is many to many for subjects and category👍

Here is the code try this.


public function categories()
{
    return $this->belongsToMany(SubjectCategory::class, 'subject_category', 'subject_category_id');
}
Sinnbeck's avatar

@bashiro It seems you accidentally set your own answer as the best? Wasn't it the links provided by @tray2 that helped you solve the issue? :)

1 like

Please or to participate in this conversation.