2014-02-10 31 views
3

我只是發現了Laravel,並進入了雄辯的ORM。但是我在下面這個小問題上磕磕絆絆。查詢與Laravel 4.1中的雄辯ORM在同一張表中的關係

我有三個表具有下列結構和數據:

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 
-------------------------- 

如你所見,我們在單詞表中的父/子關係。

的文件模型定義爲以下

class Documents extends Eloquent { 

protected $table = 'documents'; 

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

} 

而這句話型號:

class Word extends Eloquent { 

protected $table = 'words'; 

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


} 

現在我的問題是,我想找回已翻譯單詞的文檔,所以我認爲這將做到這一點:

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

但我得到0結果,所以我查了查詢,Eloqu耳鼻喉科產生和使用:

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 

的問題是,它不使用別名的表,我的查詢應該更喜歡這個有什麼工作(和它):

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 

但我如何用Eloquent ORM來做到這一點?

非常感謝您的幫助,希望我很清楚。

回答

5

在詞模型,改變

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

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

這種方式,我們說的是Laravel使用查詢時的雄辯創建別名。我沒有測試其他案例,但我認爲它會起作用。

+0

在這裏,它並沒有發生過一次。總是自己_... – diegofelix

+0

您是否在數據庫配置文件中設置了表前綴? 「前綴」是我在我的配置中設置的。 – Gabor

+0

如果您在數據庫配置中添加了「前綴」,則默認行爲是您的所有表都必須是前綴前綴,如:prefixdocuments,prefixwords。所以你必須在你的雄辯模型中改變它。 – diegofelix