mercredi 16 décembre 2015

Laravel 5.1 Returning concatenated fields though eager loading

I'm currently having an issue retrieving a concatenated cell containing all store comments in one cell.

The way my database is set up: One store can have multiple comments, and every comment must relate back to the user.

Returning this normally though eager loading is fine, however what I'm trying to achieve is a single cell that contains a list of every comment for a store such as:

store1{Comments:["10-10-2015 - Comment 1 - User 1\n10-10-2015 - Comment 2 - User2"]},
store2{Comments:["10-10-2015 - Comment 3 - User3\n10-10-2015 - Comment 4 - User4\n10-10-2015 - Comment 5 - User5"]}

The two different methods I've tried to get this to work are: selecting the concatenated columns when I retrieve the stores:

return $stores = Store::with('StoreComment','StoreComment.CreatedBy')
->select(DB::raw("group_concat(DATE_FORMAT(storecomment.created_at,'%Y-%m-%d'), ' - ', Comment, ' - ', ShortName, '\n'  ORDER BY storecomment.created_at DESC SEPARATOR '') as storecomments"))
->groupBy('store.StoreID')
->get();

Which resulted in some field not found errors that I couldn't resolve.

I've also tried this approach in my store model:

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

However this only retrieves an empty cell.

Does anyone know where I've gone wrong in either approach? Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire