Created
December 20, 2018 02:21
-
-
Save purplefeel/e53e07510001213c11b83a999eab1a7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 } | |
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 } | |
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 } | |
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 } | |
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 } | |
`Book` table above. | |
Write your code in the proposal to get this result from Book table, but you must use LARAVEL framework and Eloquent ORM model. | |
`Result` you need to get by query. | |
{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] } | |
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] } | |
// Book model | |
class Book extends Model { | |
protected $table = 'Book'; | |
} | |
// In your controller | |
function getBooksByAuthor() { | |
$all_arr = Book::all(); | |
$author_arr = Book::select('DISTICNT(author)')->get(); | |
$temp_arr = array(); | |
foreach ($all_arr as $row) { | |
if (!isset($temp_arr[$row->author])) { | |
$temp_arr[$row->author] = array(); | |
} | |
array_push($temp_arr[$row->author], $row->title); | |
} | |
foreach ($author_arr as $row) { | |
$row->books = $temp_arr[$row->author]; | |
} | |
return $author_arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment