在Laravel 5.1中加载雄辩的模型关系子节点

时间:2018-07-21 07:30:37

标签: php laravel eloquent laravel-5.1

我无法返回$ 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->副本,它可以工作,但是我当然不能在foreach()循环中插入它。 请帮忙。

1 个答案:

答案 0 :(得分:1)

$availablePrinter->copies()返回查询构建器,您必须使用$availablePrinter->copies这是可以循环添加的Collection,请尝试

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

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

旁注,还要在belongsTo模型中修复您的PrinterCopy关系,应该是这样

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