Model relations and Querying Laravel

Posts model may look like below

    public function tags(){
        return $this->hasMany('App\Models\Posttag','post_id','post_id');
    }
    public function user(){
        return $this->belongsTo('App\Models\User','user_id');
    }
    public function comments(){
        return $this->hasMany('App\Models\Comment','post_id','post_id');
    }
    public function comments_count(){
        return $this->hasOne('App\Models\Comment','post_id','post_id')->selectRaw('post_id, count(*) as aggregate')->groupBy('post_id');
    }

Then we can query data like so

	   $data = Post::with(['tags','comments' => function($query){
			$query->with(array('owner'))->orderBy('created_at','DESC')->limit(1);
			},'user' => function($query){
                                  $query->select('id','name','profile_pic');
                       }])->get();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s