【问题标题】:Laravel 5.1 Returning concatenated fields though eager loadingLaravel 5.1通过急切加载返回连接字段
【发布时间】:2016-03-22 15:02:59
【问题描述】:

我目前在检索包含一个单元格中的所有商店 cmets 的串联单元格时遇到问题。

我的数据库设置方式:一个商店可以有多个 cmets,每个评论都必须与用户相关。

虽然急切加载正常返回这个很好,但是我想要实现的是一个包含商店每个评论列表的单个单元格,例如:

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"]}

我尝试使用的两种不同方法是:在检索商店时选择连接列:

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();

这导致某些字段未找到我无法解决的错误。

我也在商店模型中尝试过这种方法:

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');
}       

但是这只会检索一个空单元格。

有谁知道我在这两种方法中哪里出错了?谢谢!

【问题讨论】:

  • 这样做的原因是什么?比如为什么不在视图中按照你想要的方式格式化结果
  • @amirbar 此代码用于报告工具,其中需要针对下载中的每个商店获取所有商店 cmets。我可以在控制器中对其进行格式化,但我认为这样做效率很低。
  • 是的,我会在一些格式化程序类中格式化它,而不是在数据库中

标签: php laravel laravel-5 eloquent


【解决方案1】:

在StoreComet Model中定义评论的用户关系:

class StoreComment extends Model
{
  public function user()
  {
    return $this->belongsTo('App\User','column name in which you have stored user id in store_comment table');
  }
}

class Store extends Model
{
  public function StoreComment()
  {
    return $this->hasMany('App\StoreComment','StoreID','StoreID')->with('user');
  }
}

现在像这样获取:

$stores = Store::with('StoreComment');

如果您想为 StoreComment 自定义属性,请在 StoreComment 模型中这样定义:

class StoreComment extends Model
{
  protected $appends = ['formattedComment'];

  public function user()
  {
    return $this->belongsTo('App\User','column name in which you have stored user id in store_comment table');
  }

  public function getFormattedCommentAttribute()
  {
    return $this->Comment.' - '.$this->ShortName;
  }
}

【讨论】:

    猜你喜欢
    • 2014-08-30
    • 2020-09-12
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    相关资源
    最近更新 更多