Search code examples
phpmysqllaraveleloquentmany-to-many

Laravel whereHas on M2M having same attribute


I have two models, word and meaning, in a Many-to-Many relationship.

Model Meaning:

public function words(){
        return $this->belongsToMany(Word::class);
}

Model Word:

public function meanings(){
        return $this->belongsToMany(Meaning::class);
}

I need to find all the meanings that have a word equal to their self name. I tried:

$meanings = Meaning::whereHas('word', function ($query) { 
               $query->where('meaning.name', 'word.name'); 
            })->get();

But this searches meanings that are called literally "word.name". Any idea ? Thanks!


Solution

  • there is a special 'where' for this case, it 's 'whereColumn', this where meant to make comparison between two columns:

    $meanings = Meaning::whereHas('word', function ($query) { 
                   $query->whereColumn('meaning.name', 'word.name'); 
                })->get();
    

    more details on: https://laravel.com/docs/7.x/queries#where-clauses