i am very opinionated in this (so do not take me very seriously in this case), but i hate it. every time i try to "morphize" such a simple thing like this, it starts very nice and clean and i like it, but it sooner or later grows to monstrosity with custom hacks to tweak around tiny differences, IDE doesnt work for all of them... and so on. every time i say no more, but then i do it again 😬
Inheritance and database
Hello,
I have a Laravel project for which I need to handle devices. To explain more easy, I explain with a media library.
A media library can lend books, games, CDs, DVDs, ... which are article types.
Each article has a title, but each article of a given type has custom properties that are different from another article of another type.
articles
- id
- title
- articleable_id
- articleable_type
books
- id
- pages_number
- ...
- article_id
dvds
- id
- duration
- ...
- article_id
First question : what do you think about this idea ?
Second question : how is it possible to handle all properties (article properties and book properties) in the same model ? It could be done with inheritance.
public class Article extends Model
{
protected $table = 'articles';
public function details()
{
return $this->morphTo('details');
}
}
public class Book extends Model
{
protected $table = 'books';
public function article()
{
return $this->morphOne('details');
}
}
What could be very interesting is to be able to hide the parent class (not remove it, but just hide it) and save and update the data only from the child classes.
For the moment I don't see any other way than saving the parent model and then saving the child model.
$article = Article::create($request->all());
$book = new Book;
$book->fill($request->all());
$book->article_id = $article->id;
$book->save();
Is it possible to handle this under the hood and handle only the book model inside the business logic ? The classes could look like this.
public class Article extends Model
{
}
public class Book extends Article
{
}
Thanks for your help.
V
Please or to participate in this conversation.