php - Get eloquent model and all its relationships with one query in Laravel -
the problem
is there way eloquent model , all relationships using 1 query?
example scenario:
you have both post , comment eloquent models.
add relationships in model class using hasmany('comment') , belongsto('post') respectively.
now i've been doing retrieve both post , comments:
$post = post::find($id); $post->comments; return $post; this returns beautiful jsonobject. problem is, way, using 2 queries. that's not great.
workaround
two alternatives come mind:
- using
joinstatements in order make query want. eloquent more elegant. - leveraging cache class in order make fewer queries in future (this, anyway later on).
any ideas?
in eloquent can this
$post = post::with('comments')->find($id); return $post; edit: not run query join in mysql single query in eloquent.
Comments
Post a Comment