Reputation: 3202
i was previously worked relationship in laravel. so recently i moved to core php ,so i am trying for one to many relationship.but it always return separate record. i have following tables
authors
id | username | created_by | updated_by
books
id | author_id | book_name | book_image |
Query
select * from authors left join books on author.id=books.author_id
i am looking my result somethink like this
Array
(
[0] => Array
(
[id] => 1
[name] => Norm
[books] => Array
(
[0] =>Array
(
[id] => 4
[book_name] => great wall
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
[1] =>Array
(
[id] => 6
[book_name] =>new book
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
)
)
[1] => Array
(
[id] => 2
[name] => Norm
[books] => Array
(
[0] =>Array
(
[id] => 2
[book_name] => amazing star
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
[1] =>Array
(
[id] => 3
[book_name] =>way of journy
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
)
)
but in core php i am getting ouput
Array
(
[0] => Array
(
[id] => 1
[username] => david
[created_by] =>
[user_id] => 1
[books] => book1
)
[1] => Array
(
[id] => 2
[username] => david
[created_by] =>
[user_id] => 1
[books] => book2
)
[2] => Array
(
[id] => 3
[username] => david
[created_by] =>
[user_id] => 1
[books] => book3
)
[3] => Array
(
[id] => 5
[username] => miller
[created_by] =>
[user_id] => 2
[books] => new1
)
[4] => Array
(
[id] => 6
[username] => miller
[created_by] =>
[user_id] => 2
[books] => new2
)
)
so i want to display author name with many books.can any one help me,how i can achieve this
Upvotes: 1
Views: 225
Reputation: 641
class Author extends Model
{
/**
* Get the books for the author.
*/
public function books()
{
return $this->hasMany('App\Book');
}
}
...
class Book extends Model
{
/**
* Get the atuhor that owns the book.
*/
public function post()
{
return $this->belongsTo('App\Author');
}
}
Upvotes: 1