在 Laravel 5.1 中加载 Eloquent 个模型关系子节点

Load Eloquent Model Relationships Child Nodes in Laravel 5.1

我不能 return $parent->child() |我得到空值;

父模型

class PrinterSetting extends Model
{
    protected $table = 'printer_settings';
    //fillables here
    protected $with = ['copies'];

    public function copies(){
        return $this->hasMany(\App\DB\PrinterCopy\PrinterCopy::class, 'printer_id');
    }

}

童模

class PrinterCopy extends Model
{
    protected $table = 'printer_copies';

    public function printer(){
        return $this->belongsTo(\App\DB\PrinterSetting\PrinterSetting::class, 'id', 'printer_id');
    }

}

控制器中的代码:

$availablePrinters = $this->printerSetting->where('is_active', 1)->get();
foreach($availablePrinters as $availablePrinter)
{
   //working
   foreach($availablePrinter->copies() as $copy)
   {
   //Not working
   }
}

我找不到它不起作用的原因。 我试图转储 $availablePrinter->copies 并且它有效,但当然我不能将它插入 foreach() 循环。 请帮忙。

$availablePrinter->copies() return 查询构建器,你必须使用 $availablePrinter->copies 这是你可以在循环中添加的集合,试试这个

$availablePrinters = $this->printerSetting->where('is_active', 1)->get();

foreach($availablePrinters as $availablePrinter)
{
   //working
   foreach($availablePrinter->copies as $copy)
   {
       dd($copy)
   }
}

旁注,同时修复 PrinterCopy 模型中的 belongsTo 关系,它应该是这样的

public function printer(){
   return $this->belongsTo(\App\DB\PrinterSetting\PrinterSetting::class,'printer_id');
}