php - 在 Laravel 4.1 中使用 Eloquent ORM 在同一个表中查询关系

标签 php laravel laravel-4 eloquent

我刚刚发现 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 在使用您的查询时在 Eloquent 中创建一个别名。我没有测试其他情况,但我认为它会起作用。

关于php - 在 Laravel 4.1 中使用 Eloquent ORM 在同一个表中查询关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21683035/

相关文章:

php - 如果数据库记录中包含空值,如何将空值设置为数据字段?

javascript - $.get json数组复制

php - Laravel 中的 session flash 消息超时

laravel - 如何将 css 类应用到 Laravel Collective Select

php - 基于其他用户输入的 Laravel 验证输入

php - 每次保存时如何将 NOW() 保存到我的 Laravel Eloquent 模型中的同一字段?

php - 将参数传递给 laravel 中的 Restful Controller

php - Slim框架的路由问题

php - Laravel 在一个函数中加载多个 View

php - 如何部署 CodeIgniter/Laravel 应用程序