我正在嘗試與一些雄辯的表建立關系,并嘗試制作實際從兩個關系表中檢索資料的 api。來一張照片就明白了。

讓我們考慮employees 和employee_types 來簡化問題。我的遷移代碼看起來像
Schema::create('os_employee_types', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('priority')->default(0);
$table->tinyInteger('status')->default('1');
$table->timestamps();
});
和,
Schema::create('os_employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->bigInteger('employee_type')->unsigned()->nullable();
$table->timestamps();
$table->foreign('employee_type')->references('id')->on('os_employee_types');
});
這里在員工表中,employee_type 是員工型別表中的外鍵,與員工型別表上的 id 相關。我的模型看起來像
class OsEmployeeType extends Model
{
public function OsEmployee()
{
return $this->hasOne(OsEmployee::class);
}
}
和,
class OsEmployee extends Model
{
public function OsEmployeeType()
{
return $this->belongsTo(OsEmployeeType::class);
}
}
現在控制器看起來像
public function check(){
$employee = OsEmployee::with('OsEmployeeType')->get();
return new OsEmployeeMaxCollection($employee);
}
我得到了回應
{
"data": [
{
"id": 56,
"name": "Arafat Rahman",
"employee_type": 2,
"created_at": "2022-03-01T11:23:05.000000Z",
"updated_at": "2022-03-01T11:23:05.000000Z",
}
]
}
這是來自 os_employee 表的絕對資料。但我想要員工型別的資料。我想要這樣的回應
{
"data": [
{
"id": 56,
"name": "Arafat Rahman",
"employee_type": {
"id": 2,
"name": "employee_type 1",
"priority": 10,
"status": 1
},
"created_at": "2022-03-01T11:23:05.000000Z",
"updated_at": "2022-03-01T11:23:05.000000Z",
}
]
}
這是 dd($employee)

OsEmployeeMaxCollection 看起來像
class OsEmployeeMaxCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
我的錯誤或錯誤是什么?我怎樣才能得到像我的描述一樣的資料。
uj5u.com熱心網友回復:
public function check(){
return OsEmployee::with('OsEmployeeType')->get();
}
這應該有效。如果沒有 OsEmployeeType,則此欄位不應為空。
如果你想要json回應
public function check(){
return OsEmployee::with('OsEmployeeType')->get()->toJson();
}
并將您的代碼遷移更改為:
Schema::create('os_employees', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->bigInteger('employee_type_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('employee_type_id')->references('id')->on('os_employee_types');
});
和你的模型:
class OsEmployee extends Model
{
public function OsEmployeeType()
{
return $this->belongsTo(OsEmployeeType::class, 'employee_type_id');
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/435152.html
上一篇:如果字串包含文本,我如何創建
