'Method' vs 'Dynamic Property' in Eloquent ORM with Laravel? -


i want count number of posts belongs tag. should use method or dynamic property?

<?php  class tag extends eloquent {      public function posts()     {         return $this->belongstomany('post');     }      public function postscount()     {         return count($this->posts);     }      public function getpostscountattribute()     {         return count($this->posts);     }  } 

so in template should use dynamic property:

{{ $tag->postcount }} 

or method:

{{ $tag->postcount() }} 

excerpt documentation of laravel 4 regarding eloquent's dynamic properties (accessor) in relationships (bold mine):

eloquent allows access relations via dynamic properties. eloquent automatically load relationship you, , smart enough know whether call (for one-to-many relationships) or first (for one-to-one relationships) method. accessible via dynamic property same name relation.

that said, using method defined database relationship or dynamic property (accessor) behave differently.

if issue post count using method follows:

$count = $tag->posts()->count(); 

that generate proper sql count aggregate function.

in other hand, if issue post count using dynamic property (accessor) follows:

$count = count($tag->posts); 

that fetch posts, convert them array of objects, counting number of element of array.

in case, choice should depend of usage of posts related tag. if want count, use method , aggregate function. but, if apart counting doing else posts, use dynamic property (accessor).


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -