简体   繁体   中英

Laravel 5.1 relationship not working when using eager loading

I have a store and a comments model set up, and I've created a relationship that should return all of the store comments concatenated together. This is working fine until I attempt to use eager loading, then the relationship will always return NULL.

This is the relationship:

  public function FormattedStoreComments()
{
  return $this->hasOne('App\Models\StoreComment','StoreID','StoreID')
              ->select(DB::raw("group_concat(DATE_FORMAT(StoreComment.created_at,'%Y-%m-%d'), ' - ', ShortName, ' - ', Comment, '\n'  ORDER BY StoreComment.created_at DESC SEPARATOR '') as Comments"))
              ->join('users','StoreComment.created_by','=','users.UserID')
              ->groupBy('StoreID')
              ->whereNull('StoreComment.deleted_at')
              ->orderBy('StoreComment.created_at','DESC');
}

Is there any reason why this shouldn't be working with eager loading?

Using Eloquent scopes, Try this:

   public function scopeFormattedStoreComments($query)
   {
    return  $query->hasOne('App\Models\StoreComment','StoreID','StoreID')
          ->select(DB::raw("group_concat(DATE_FORMAT(StoreComment.created_at,'%Y-%m-%d'), ' - ', ShortName, ' - ', Comment, '\n'  ORDER BY StoreComment.created_at DESC SEPARATOR '') as Comments"))
          ->join('users','StoreComment.created_by','=','users.UserID')
          ->groupBy('StoreComment.StoreID')
          ->whereNull('StoreComment.deleted_at')
          ->orderBy('StoreComment.created_at','DESC');
   }

and then you can call it like this :

$formattedStoreComments = Store::formattedStoreComments()->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM