查询 Laravel 8 中的一对多关系
Query One to Many Relation in Laravel 8
我有用户和学生的一对多关系。
型号User.php
public function students()
{
return $this->hasMany(Student::class);
}
型号Student.php
public function user(){
return $this->belongsTo(User::class);
}
并在 Controller.php
public function show(){
$users = User::with('students')find(5);
return response()->json($users);
}
它将 运行 和 return json
{
"id": 5,
"email": "student1@test.com",
"email_verified_at": null,
"created_at": "2021-06-27T01:52:28.000000Z",
"updated_at": "2021-06-27T01:52:28.000000Z",
"students": [
{
"id": 1,
"user_id": 5,
"firstname": "Ms",
"lastname": "Zee",
"studentPhone": "08515xxxxxxx",
"studentAddress": "my address"
},
{
"id": 5,
"user_id": 5,
"firstname": "my Name",
"lastname": "k",,
"studentPhone": "085xxxxxx",
"studentAddress": "my address",
}
]
}
我可以在学生中自定义 select,只显示名字和姓氏吗?
您应该为此使用 API 资源。这是官方文档的link:https://laravel.com/docs/8.x/eloquent-resources
您的学生 collection 可能看起来像这样:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class StudentCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'firstname' => $this->firstname,
'lastname' => $this->lastname,
];
}
}
我有用户和学生的一对多关系。
型号User.php
public function students()
{
return $this->hasMany(Student::class);
}
型号Student.php
public function user(){
return $this->belongsTo(User::class);
}
并在 Controller.php
public function show(){
$users = User::with('students')find(5);
return response()->json($users);
}
它将 运行 和 return json
{
"id": 5,
"email": "student1@test.com",
"email_verified_at": null,
"created_at": "2021-06-27T01:52:28.000000Z",
"updated_at": "2021-06-27T01:52:28.000000Z",
"students": [
{
"id": 1,
"user_id": 5,
"firstname": "Ms",
"lastname": "Zee",
"studentPhone": "08515xxxxxxx",
"studentAddress": "my address"
},
{
"id": 5,
"user_id": 5,
"firstname": "my Name",
"lastname": "k",,
"studentPhone": "085xxxxxx",
"studentAddress": "my address",
}
]
}
我可以在学生中自定义 select,只显示名字和姓氏吗?
您应该为此使用 API 资源。这是官方文档的link:https://laravel.com/docs/8.x/eloquent-resources
您的学生 collection 可能看起来像这样:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class StudentCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'firstname' => $this->firstname,
'lastname' => $this->lastname,
];
}
}