laravel 5.1:如何从模型中获取嵌套关系?

laravel 5.1 : how can i get nested relation from model?

我对 laravel 模型关系有疑问并在 eloquent class 中使用它们。我的问题是:

我有这样一个模型:

class TransferFormsContent extends Model
{

 public function transferForm()
    {
        return $this->belongsTo('App\TransfersForms','form_id');
    }
}

在 transferForm 中我有这样的关系的另一面:

  public function transferFormsContent()
{
    return $this->hasMany('App\TransferFormsContent', 'form_id', 'id');
}

同样在 transferForm 中,我与员工的另一个关系是这样的:

class TransfersForms extends Model
{
     public function employee()
        {
            return $this->belongsTo('App\User','employee_id');
        }
}

现在,如果我想从 "TransferFormsContent" 获取记录,其 "transferForm " 由员工提供。我该怎么做?

我现在如果我想得到 "TransferFormsContent" 只有 "transferForm " 我可以从这里使用 :

 $row = $this->model
            ->with('transferForm'); 

但是如果我想让 transferForm 也和它的员工在一起呢?

好的,我发现:

只有你可以这样做:

 $row = $this->model
            ->with('transferForm.employee')

现在您有一条来自 "TransferFormsContent" 的记录,其 "transferForm " 由员工提供。

您可以使用带点符号的嵌套预加载:

$row = $this->model
        ->with('transferForm.employee'); 

或者你可以使用闭包:

$row->$this->model
        ->with(['transferForm' => function($q) {
              $q->with('employee')
}]); 

当您需要按员工排序或过滤时,第二种方法很有用