[英]Laravel 5.1 relationship not working when using eager loading
我已經建立了一個商店和一個評論模型,並且創建了一個關系,該關系應該返回所有串聯在一起的商店評論。 直到我嘗試使用緊急加載,此方法才能正常工作,然后該關系將始終返回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');
}
有什么原因不應該使它在急切加載中起作用?
使用雄辯的范圍,請嘗試以下操作:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.