[英]Query relation in same table with Eloquent ORM in Laravel 4.1
我剛剛發現了Laravel,並進入了Eloquent 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結果,所以我檢查了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
問題是它不使用表的別名,我的查詢應該更像這樣工作(它確實):
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做到這一點?
非常感謝你的幫助,希望我足夠清楚。
在Word模型中,更改
public function translation()
{
return $this->hasOne('Word', 'parent_id');
}
至
public function translation()
{
return $this->belongsToMany('Word', 'words', 'id', 'parent_id');
}
通過這種方式,我們告訴Laravel在使用您的查詢時在雄辯中創建別名。 我沒有測試其他情況,但我認為它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.