Laravel改变了雄辩的级联序列

时间:2018-05-29 06:48:39

标签: php laravel eloquent

我有$persons集合,其中包含带有关系的$person雄辩对象模型数组。 人有很多帐户,帐户有一个en。

例如,如果想要访问en的方式是e1属性:$person->accounts[0]->en

如何转换$person级联序列:

person=>{
  p1,
  p2,
  accounts{
    a1,
    a2,
    en{
      e1,
      e2
    }
  }
}

成像:

en{
  e1,
  e2,
  accounts{
    a1,
    a2
  },
  person{
    p1,
    p2
  }
}

更改后我想要这样的$en->accounts->person->p1

1 个答案:

答案 0 :(得分:1)

您可以在En模型中创建一个关系,指定与帐户模型的关系。

public function account(){
        return $this->belongsTo(Account::class);
    }

在Account模型中,创建与Person模型的关系。

public function person(){
        return $this->belongsTo(Person::class);
}

然后您就可以按照

的要求检索数据
//en should have account and account should be associated with person
$en->accounts->person->get();