Laravel Close relationship with advanced models

I am working on a site with advanced models, for example.

class Asset extends Model { public function project() { return $this->belongsTo(Project::class); } } class Video extends Asset { } 

Should I establish the same belongsTo Eloquent relationship with the extended class, or by virtue of having a parent class, will Laravel do the rest?

In addition, is there any documentation anywhere that describes in detail how to structure such relationships (for example, from the point of view of controllers)? I cannot find anything on the (usually excellent) Laracasts website.

+5
source share
1 answer

You do not need to specify the extended method twice if you do not want to override it with other behavior.

I personally use a lot of inheritance in my applications, and it works as expected, every relation continues to work and query, using the parent defaults or certain protected variables that you declare.

For example, if you declare protected $table = 'foo' , it will also accept this variable to fulfill its request or you can override it on the child server to request another table from the parent.

In terms of documentation, the reason why you do not find a lot of information, I think, because it is more a problem with PHP and OOP than with a specific structure.

If you want to declare polymorphic relationships, which are actually a common way to implement multiple inheritance in your SQL, Laravel has your back, with special Eloquent relationships and migration commands , for example $table->morphs('asset'); .

Hope this helps you.

+2
source

Source: https://habr.com/ru/post/1269032/


All Articles