Gab*_*bor 3 php laravel eloquent laravel-4
我刚刚发现了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
--------------------------
Run Code Online (Sandbox Code Playgroud)
如您所见,我们在单词表中有父/子关系.
文档模型定义如下
class Documents extends Eloquent {
protected $table = 'documents';
public function words()
{
return $this->belongsToMany('Word', 'documents_words', 'document_id');
}
}
Run Code Online (Sandbox Code Playgroud)
和模型:
class Word extends Eloquent {
protected $table = 'words';
public function translation()
{
return $this->hasOne('Word', 'parent_id');
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我想要检索具有翻译单词的文档,所以我认为这样做:
$documents = Documents::whereHas('words', function($q)
{
$q->has('translation');
})
->get();
Run Code Online (Sandbox Code Playgroud)
但我得到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
Run Code Online (Sandbox Code Playgroud)
问题是它不使用表的别名,我的查询应该更像这样工作(它确实):
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
Run Code Online (Sandbox Code Playgroud)
但是我怎么能用Eloquent ORM做到这一点?
非常感谢你的帮助,希望我足够清楚.
小智 5
在Word模型中,更改
public function translation()
{
return $this->hasOne('Word', 'parent_id');
}
Run Code Online (Sandbox Code Playgroud)
至
public function translation()
{
return $this->belongsToMany('Word', 'words', 'id', 'parent_id');
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我们告诉Laravel在使用您的查询时在eloquent中创建别名.我没有测试其他情况,但我认为它会起作用.
| 归档时间: |
|
| 查看次数: |
2927 次 |
| 最近记录: |