Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

akc4's avatar
Level 1

one to many relation with two foreignId's

I have 3 separate tables:

Jobs: (lists jobs)

-id 
-name 
-description 

Keywords: (lists the name of keywords)

-id
-name

KeywordsList: (creates the relation between Jobs table and Keywords table)

-keyword_id
-job_id

Adding this to my Jobs model returns all the keywords from the KeywordList but how do I get the keyword's name (which are stored in Keywords)

protected function keywords() {
        return $this->hasMany(KeywordList::class, 'job_id', 'id');
    }
0 likes
1 reply
SilenceBringer's avatar
Level 55

@akc4 assuming you KeywirdList model has keyword relation (belongsTo Keyword model), you can use it like so:

$jobs = Jobs::with('keywords.keyword')->all();

and the you can output keywords like

@foreach ($jobs as $job)
    @foreach ($job->keywords as $jobKeyword)
         {{ $jobKeyword->keyword->name }}
    @endforeach    
@endforeach

but really your relationships between Job and Keyword is many to many https://laravel.com/docs/8.x/eloquent-relationships#many-to-many and your KeywordList table is pivot table. So it make sence to refactor it

2 likes

Please or to participate in this conversation.