Hi there, I'm new to laravel and I'm asking myself how to do it better:
I have a model (Book) wich references another model (Person) in multiple different ways.
There are the following database tables:
| books | |
| -------------------- | ------------ |
| int id | |
| int author_id | -> person.id |
| int lecturer_id | -> person.id |
| string title etc... | |
| persons |
| ------------------ |
| int id |
| string name etc... |
| pivot_book_reviewer | |
| ------------------- | ------------ |
| int book_id | -> book.id |
| int reviewer_id | -> person.id |
So a book references persons in 3 ways. There is a book's author, it's lecturer and multiple reviewers.
My models looks like this:
class Book extends Model {
//[...]
public function author(){
return $this->hasOne('App\Person', 'id', 'author_id');
}
public function lecturer(){
return $this->hasOne('App\Person', 'id', 'lecturer_id');
}
public function reviewers(){
return $this->belongsToMany('App\Person', 'pivot_book_reviewer', 'reviewer_id', 'book_id');
}
}
class Person extends Model {
//[...]
public function book_author(){
return $this->hasMany('App\Book', 'author_id', 'id');
}
public function book_lecturer(){
return $this->hasMany('App\Book', 'lecturer_id', 'id');
}
public function books_reviewer(){
return $this->belongsToMany('App\Book', 'pivot_book_reviewer', 'book_id', 'reviewer_id');
}
}
This seems to work, but is this the right way of doing it? Obviously not.
But what is the right way? Should I create a child class for every type of person?
A little hint would be very helpful! :)