Query ratio in the same table with Eloquent ORM in Laravel 4.1

I just open Laravel and get into Eloquent ORM. But I stumble on a small problem, which is as follows.

I have three tables with the following structures and data:

words

id | language_id | parent_id | word
-------------------------------------------
1  | 1           | 0         | Welcome
-------------------------------------------
2  | 2           | 1         | Bienvenue
-------------------------------------------

documents

id | title
---------------------
1  | Hello World
---------------------

documents_words

document_id | word_id
--------------------------
1           | 1
--------------------------

As you can see, we have a parent / child ratio in the word table.

The document model is defined as follows

class Documents extends Eloquent {

protected $table = 'documents';

public function words()
{
    return $this->belongsToMany('Word', 'documents_words', 'document_id');
}

}

And a model of words:

class Word extends Eloquent {

protected $table = 'words';

public function translation()
{
    return $this->hasOne('Word', 'parent_id');
}


}

Now my problem is that I want documents that translate words, so I thought that would do this:

$documents = Documents::whereHas('words', function($q)
{
    $q->has('translation');
})
->get();

But I get 0 results, so I checked the query that generates and uses Eloquent:

 select * from `prefix_documents`
 where
 (
select count(*) from 
`prefix_words`

inner join `prefix_documents_words` 

on `prefix_words`.`id` = `prefix_documents_words`.`word_id` 

where `prefix_documents_words`.`document_id` = `prefix_documents`.`id` 

and (select count(*) 
from `prefix_words` 
where `prefix_words`.`parent_id` = `prefix_words`.`id`) >= 1

  ) >= 1

The problem is that it does not use aliases for tables, that my query should be more like this in order to work (and it does):

 select * from `prefix_documents`
 where
 (
select count(*) from 
`prefix_words`

inner join `prefix_documents_words` 

on `prefix_words`.`id` = `prefix_documents_words`.`word_id` 

where `prefix_documents_words`.`document_id` = `prefix_documents`.`id` 

and (select count(*) 
from `prefix_words` as `w`
where `w`.`parent_id` = `prefix_words`.`id`) >= 1

  ) >= 1

But how can I do this with the Eloquent ORM?

, , .

+3
1

Word Model

public function translation()
{
    return $this->hasOne('Word', 'parent_id');
}

public function translation()
{
    return $this->belongsToMany('Word', 'words', 'id', 'parent_id');
}

Laravel . , , .

+5

All Articles