Laravel 4 是否有可能以雄辩的方式加载任意查询?

Laravel 4 是否有可能以雄辩的方式加载任意查询?,laravel-4,eloquent,eager-loading,Laravel 4,Eloquent,Eager Loading,我在Laravel 4工作,我有一个具有多个教育档案的儿童模型: class Child extends EloquentVersioned { public function educationProfiles() { return $this->hasMany('EducationProfile'); } } 如果我想获得每个10岁以下儿童的所有教育概况,这将很容易: Child::where('date_of_birth','>','2004

我在Laravel 4工作,我有一个具有多个教育档案的儿童模型:

class Child extends EloquentVersioned 
{
public function educationProfiles()
    {
        return $this->hasMany('EducationProfile');
    }
}
如果我想获得每个10岁以下儿童的所有教育概况,这将很容易:

Child::where('date_of_birth','>','2004-03-27')->with('educationProfiles')->all();
但是(正如我所做的)我想用with()来获取每个孩子的教育概况的计算值,比如:

SELECT `education_profiles`.`child_id`, GROUP_CONCAT(`education_profiles`.`district`) as `district_list`
理论上,with()只适用于关系,因此我是否有任何选项将
地区列表
字段关联到我的子模型

编辑:实际上,我想知道with('educationProfiles')是否生成与以下内容等效的SQL:

EducationProfile::whereIn('id',array(1,2,3,4))
或者它是否真的等同于

DB::table('education_profiles')->whereIn('id',array(1,2,3,4))

我问的原因是,在前一种情况下,我得到的是模型,如果是后一种情况,我得到的是未建模的数据,因此我可能会把它搞得一团糟。不过,我假设with()会生成一组额外的模型。有人想更正或确认吗?

好的,我想我已经破解了这个难题。不,不可能加载任意查询。然而,Fluent查询生成器提供了这些工具,使得手动复制即时加载相对容易

首先,我们利用原始查询:

$query = Child::where('date_of_birth','>','2004-03-27')->with('educationProfiles');
$children = $query->get();
$eagerIds = $query->lists('id');
接下来,使用
$IDs
过滤
DB::table('education_profile')
,过滤方式与
with('educationProfiles')
过滤
EducationProfile::…

$query2 = DB::table('education_profile')->whereIn('child_id',$eagerIds)->select('child_id', 'GROUP_CONCAT(`education_profiles`.`district`) as `district_list`')->groupBy('child_id');
$educationProfiles = $query2->lists('district_list','child_id');
现在我们可以遍历
$children
,只需查找每个条目的
$educationProfiles[$children->id]


好的,是的,这是一个明显的构造,但我以前没有看到它作为一种加载任意计算的方式被明确地放置在任何地方。

您可以像这样在hasMany()调用中添加where子句:

public function educationProfilesUnderTen() {
    $ten_years_ago = (new DateTime('10 years ago'))->format('Y-m-d');
    return $this->hasMany('EducationProfile')->where('date_of_birth', '>', $ten_years_ago)
}
是的,刚刚测试过,with()生成的SQL等价于EducationProfile:,而不是DB::table。真倒霉