Have you tried joins => https://laravel.com/docs/9.x/queries#joins
Mar 1, 2022
4
Level 1
Relationship with array/object structure
Hello there,
I have 2 models like this:
Student model
class Student extends Model
{
use HasFactory;
public function department()
{
return $this->belongsTo(Department::class);
}
}
Department model
class Department extends Model
{
use HasFactory;
public function students()
{
return $this->hasMany(Student::class);
}
}
But I want to get the result of with relationship as one object like this:
{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"department_id": 1,
"department.name": "IT"
}
But I get this:
{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"department_id": 1,
"department": {
"id": 1,
"name": "IT"
}
}
I know I can restructure the result but is there a way to do it in Eloquent? and what is the most efficient way to do this?
Thanks.
Level 1
1 like
Please or to participate in this conversation.