Laravel 5获取关系数据

问题描述 投票:2回答:2

我已经使用Laravel 5.5进行了应用,并使用了MySQL数据库。我有2个表人:id,name,homeplanet_id行星:id,name和外键people.homeplanet_id引用行星id

我还有2个模型:Person和Planet,以及PersonController。我可以使用在控制器中获取Person的数据

Person::find($id)->getAttributes()

但它就像

[
    id => 1
    name => Name
    homeplanet_id => 1
]

我怎样才能获得下一个数据

[
    id => 1
    name => Name
    homeplanet_id => Planet_name
]
php laravel laravel-5
2个回答
0
投票

与()方法一起使用,类似于 $ person = Person::where(array())->with('planet')->get(); //You can fetch all related data by passing multiple values for method with() 打印

{{$person->planet->name}} //where planet indicated the relation on person model as follows

planet表示人物模型的关系。

在我们的例子中 获取数据$person = Person::where(array('id'=>$id))->with('planet')->get();

在Person模型中,使用with()方法执行以下操作来获取行星:

Person extends model{
   public function panet(){
      //your relation one to one, one to many etc.....whatever
   }
}

尝试在Laravel(eloquent)和范围查询中探索渴望加载。

访问Eager loading的链接,一切都将由ORM本身完成.Link


1
投票

您可能需要一个位于您的Eloquent模型和实际返回给您的应用程序用户的JSON响应之间的转换层。

https://laravel.com/docs/5.5/eloquent-resources

因此,如果您想获得JSON,请使用资源。如果您想要这种数据格式用于Blade视图,那么转换它是个坏主意。只需使用Blade模板中的数据:

{{ $person->name }} lives on the planet {{ $person->planet->name }}

其中planetPerson模型中定义的关系名称:

public function planet()
{
    return $this->belongsTo(Planet::class, 'homeplanet_id')
}
© www.soinside.com 2019 - 2024. All rights reserved.