php – Laravel model relation within same table-ThrowExceptions

Exception or error:

I am working on a Laravel 5.7 project where I have three tables words, synonym_word and antonym_word.

  • words table has two columns id and word
  • synonym_word has three columns id, word_id and synonym_id
  • antonym_word has three columns id, word_id and antonym_id

I am storing all words, their synonyms and antonyms in Words table and referencing synonyms and antonyms in respective tables.

Word.php

class Word extends Model
{
    public function synonyms()
    {
        return $this->hasMany('App\Synonym');
    }

    public function antonyms()
    {
        return $this->hasMany('App\Antonym');
    }
}    

I am querying synonyms like this:-

$synonyms = Word::find(1)->synonyms;

The above query is giving all synonyms and their id’s from the Synonym table, but my actual synonym word is stored in Words table.

How can I get synonym words from Words table?

How to solve:
$synonymsWithWord = Word::find(1)->synonyms()->with('word')->get();

to use this, Synonyms class should have relation defined with Word as below.

class Synonym extends Eloquent {

    public function word()
    {
        return $this->belongsTo('App\Word');
    }

}

Read this same scenario for more understanding.
Trying to get a post with comments and user name

Answer´╝Ü

I solved it by using dot (.) in the query.

Word.php

class Word extends Model
{
    public function antonyms()
    {
        return $this->hasMany(Antonym::class);
    }

    public function synonyms()
    {
        return $this->hasMany(Synonym::class);
    }
}

Synonym.php

class Synonym extends Model
{
    public function word()
    {
        return $this->belongsTo(Word::class);
    }
}

WordController.php

class WordController extends Controller
{
    public function index()
    {
        $words = Word::with(['synonyms.word'])->get();
        return view('words', compact('words') );
    }   
}

Notice the dot(.) between synonyms and word.

words.blade.php

@foreach($words as $word)
    <h4>{{ $word->word }}</h4>
    @foreach($word->synonyms as $s)
        {{ $s->id }} - {{  $s->word->word }}
        <br>
    @endforeach
@endforeach

Leave a Reply

Your email address will not be published. Required fields are marked *