我只是发现Laravel,并进入了雄辩的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');
}
}
和单词model:
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在使用查询时雄辩地创建别名。我没有测试其他情况,但我认为它会起作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句