我在雄辩地获取hasmany关系数据时遇到问题。

AModel hasmany BModel
AModel hasmany CModel

AModel具有以下功能:

Public function bmodels(){
    return hasMany('BModel');
}

Public function cmodels(){
    return hasMany('CModel');
}


BModel具有以下功能:

Public function bmodels(){
    return belongsTo('AModel', amodel_id);
}


CModel具有以下功能:

Public function cmodels(){
    return belongsTo('AModel',amodel_id);
}


现在我正试图像这样

$amodels = AModel::with('bmodels','cmodels')
        ->where('status_id','2200')
        ->whereIn('eventstatus_id',['1','2'])
        ->get();


现在我想在for循环中对此进行测试。

foreach($amodels as $amodel){
    $bmodels = $model->bmodels();
    if ($amodel && $amodel->end < Carbon::now()){
        foreach ($bmodels as $bmodel){
            $cmodels = $amodel->cmodels();
            foreach($cmodels as $cmodel){
                if ($bmodel->id !== $cmodel->reservation_id || $cmodel->reservation_id != null ){
                    array_push($reservation_needed_to_enter,$bmodel->id);
                }
            }

        }
    }
}

最佳答案

您应该在模型中进行更改,使用$this来使用belongsTohasMany,例如

public function bmodels(){
    return $this->belongsTo('App\AModel','amodel_id');
}
public function bmodels(){
    return $this->hasMany('App\BModel');
}


刚编辑过您的foreach loop,请使用$amodel->bmodels代替$amodel->bmodels()

 foreach($amodels as $amodel){
        $bmodels = $amodel->bmodels;
        if ($amodel && $amodel->end < Carbon::now()){
            foreach ($bmodels as $bmodel){
                $cmodels = $amodel->cmodels;
                foreach($cmodels as $cmodel){
                    if ($bmodel->id !== $cmodel->reservation_id || $cmodel->reservation_id != null ){
                        array_push($reservation_needed_to_enter,$bmodel->id);
                    }
                }

            }
        }
    }

09-17 14:05