1
我有如下關係定義:Laravel過濾渴望裝載有取()無法正常運行
帖子:
class Post extends Model
{
use SoftDeletes;
protected $fillable = ['title','content','category_id','featured_image','slug'];
protected $dates = ['deleted_at'];
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
}
類別:
class Category extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
在我的控制器索引功能,我想獲得前3個類別(數量方面的職位)與他們的前3名最新職位。我做了,只要我沒有包括在內採取方法以下工作正常:
$cats_and_posts = Category::with(['posts'=>function($query){
$query->orderBy('updated_at','desc')->take(3)->get();
}])->withCount('posts')->orderBy('posts_count','desc')->take(3)->get();
如果我包括在內採取方法,有些類別與空帖子關係加載。這裏是dd爲「cats_and_posts」變量生成的內容:
#items: array:3 [▼
0 => Category {#261 ▶}
1 => Category {#260 ▶}
2 => Category {#243 ▼
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:5 [▶]
#original: array:5 [▶]
#relations: array:1 [▼
"posts" => Collection {#269 ▼
#items: []
}
]
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
+exists: true
+wasRecentlyCreated: false
}
]
}
沒有inner take方法,所有類別的帖子都在加載!
非常感謝一些幫助。無法弄清楚爲什麼會發生這種情況。
仍然沒有解決問題!內部查詢只返回一些類別的空集合! –