使用预先加载时,Laravel 5.1关系无法正常工作

时间:2016-04-14 09:26:50

标签: php laravel laravel-5 laravel-5.1

我设置了商店和评论模型,并且我创建了一个关系,该关系应该返回连接在一起的所有商店评论。这是正常工作,直到我尝试使用预先加载,然后关系将始终返回NULL。

这是关系:

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

有什么理由说这不应该用于预先加载?

1 个答案:

答案 0 :(得分:0)

使用Eloquent范围,试试这个:

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

然后你可以这样称呼它:

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