I am trying to build up a relation with some eloquent table and try to make api that actually retrieve data from two relational table. Here a photo to understand.
Lets consider employees and employee_types for simplify the problem. My migration code looks like
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();
});
And,
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');
});
Here in employee table, employee_type is a foreign key in employee types table that relation with id on employee type table. And my model looks like
class OsEmployeeType extends Model
{
public function OsEmployee()
{
return $this->hasOne(OsEmployee::class);
}
}
And,
class OsEmployee extends Model
{
public function OsEmployeeType()
{
return $this->belongsTo(OsEmployeeType::class);
}
}
Now the controller looks like
public function check(){
$employee = OsEmployee::with('OsEmployeeType')->get();
return new OsEmployeeMaxCollection($employee);
}
I got the response
{
"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",
}
]
}
This is absolute data from os_employee table. but I want the data with employee type. I want the response like
{
"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",
}
]
}
Here is the dd($employee)
And OsEmployeeMaxCollection looks like
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);
}
}
What was my mistake or wrong? How can I get data like my description.
CodePudding user response:
public function check(){
return OsEmployee::with('OsEmployeeType')->get();
}
This should work. If it does not have OsEmployeeType this field should not be empty.
If you want json reponse
public function check(){
return OsEmployee::with('OsEmployeeType')->get()->toJson();
}
and change your code migration to:
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');
});
And your model to:
class OsEmployee extends Model
{
public function OsEmployeeType()
{
return $this->belongsTo(OsEmployeeType::class, 'employee_type_id');
}
}