【问题标题】:Laravel 4 Eloquent relations queryLaravel 4 Eloquent 关系查询
【发布时间】:2017-01-14 00:16:33
【问题描述】:

我有一个包含主表“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->prefixes->first() 和 $qso->prefixes->last() (Qso 和 Prefix 具有 manyToMany 关系)但两者都返回 null。怎么了?

【问题讨论】:

    标签: laravel eloquent relation


    【解决方案1】:

    这是我发现有效但处理时间很长的雄辩代码:

                $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');
    

    【讨论】:

    • 如果我带走('prefixes')速度变得可以接受
    猜你喜欢
    • 2013-10-03
    • 2017-07-19
    • 2021-09-25
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多