I'm using Laravel, which is awesome, but I'm stuck on an issue with the database.
Let's say we have three tables, like so:
TABLE 1: pages
id | route | title
TABLE 2: elements
id | page_id | type
TABLE 3: content
id | element_id | data
I'd like to do a single selection for the page that will in turn select all of the elements with that page id, and for each of the elements it should select all of the content rows with the element id.
I want to have a static load_by_route($route) function in the Page model that, when called, will use the route to load and return the page info as well as the elements and content as described above. Ideally it would return a single object/array with all of this info.
Basically, I'm not sure how to chain the has_many() calls together so that I get the two-level relationship.
One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .
BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.
Look into eager loading. This should do what you want.
class Page extends Eloquent {
public function elements()
{
return $this->has_many( 'Element' );
}
}
class Element extends Eloquent {
public function contents()
{
return $this->has_many( 'Content' );
}
}
class Content extends Eloquent {}
$page = Page::with( array( 'elements', 'elements.contents' ) )->first();
https://laravel.com/docs/master/eloquent-relationships#eager-loading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With