Consider books and authors relationship. Every book belongsTo an author and 1 author hasMany books. Books table has fields like (Id,Title,Version etc) and authors have fields like (Id,Name,Address etc). Note DB columns do not follow the default laravel naming convention.
Now; I want to fetch some fields from both tables. More speficic, I want title,version,name and address fields. This is desired output:
{
Title: "Oxford Maths",
Version: "2.5",
author: "John Doe",
}
1st trial:
return Book::with('author')->get()->map(function ($book) {
return collect($book)->only(
[
'Title',
'Version',
"author"
]);
});
1st Trial Output:
{
Title: "Oxford Maths",
Version: "2.5",
author: {
Id: 1,
Name: "John Doe",
Address: "Tanzania",
deleted_at: null
}
}
2nd trial: Tried this;
return Book::with([
'author' => function($query){
$query->select('Name','Id');
}
])->get()->map(function ($data) {
return collect($data)->only(
[
'Title',
'Version',
"author"
]);
});
And this;
return Book::with('authority:name,Id')->get()->map(function ($data) {
return collect($data)->only(
[
'Title',
'Version',
"author"
]);
});
2nd Trial output:
{
Title: "Oxford Maths",
Version: "2.5",
author: {
Name: "John Doe",
Id: 1
}
}
3rd Trial:
return Book::with([
'author' => function($query){
$query->select('Name'); // *Removed foreignKey*
}
])->get()->map(function ($data) {
return collect($data)->only(
[
'Title',
'Version',
"author"
]);
});
3rd Trial output:
{
Title: "Oxford Maths",
Version: "2.5",
author: null
}
What can I do to get the desired output?