简体   繁体   English

使用急切加载时Laravel 5.1关系不起作用

[英]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. 直到我尝试使用紧急加载,此方法才能正常工作,然后该关系将始终返回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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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