Laravel 4 Eloquent relations查询

时间:2016-09-06 13:49:31

标签: laravel eloquent relation

我有一个主表和Qsos'和一堆关系。现在,当我尝试创建高级搜索时,我真的不知道如何同时查询所有关系。 Qso模型如下:

    public function band()
{
    return $this->belongsTo('Band');
}

public function mode()
{
    return $this->belongsTo('Mode');
}

public function prefixes()
{
    return $this->belongsToMany('Prefix');
}

public function user()
{
    return $this->belongsTo('User');
}

public function customization() {
    return $this->hasOne('Customization');
}

然后我的SearchController包含以下代码,必须在必要条件下返回所有Qsos的集合:

$qsos = Qso::withUser($currentUser->id)
                    ->join('prefix_qso','qsos.id','=','prefix_qso.qso_id')
                    ->join('prefixes','prefixes.id','=','prefix_qso.prefix_id')
                    ->where('prefixes.territory','like',$qTerritory)
                    ->withBand($qBand)
                    ->withMode($qMode)
                    ->where('call','like','%'.$input['qCall'].'%')
                    ->orderBy('qsos.id','DESC')
                    ->paginate('20');

然后在视图中我需要调用$ qso->前缀 - > first()和$ qso->前缀 - > last()(Qso和Prefix具有manyToMany关系)但两者都返回null。有什么问题?

1 个答案:

答案 0 :(得分:0)

以下是我发现有效的代码,但需要花费很长时间才能处理:

            $qsos = Qso::withUser($currentUser->id)
                    ->with('prefixes')
                    ->withBand($qBand)
                    ->withMode($qMode)
                    ->where('call','like','%'.$input['qCall'].'%')
                    ->whereHas('prefixes', function($q) use ($qTerritory) {
                        $q->where('territory','like',$qTerritory);
                    })
                    ->orderBy('qsos.id','DESC')
                    ->paginate('20');