Laravel过滤渴望装载有取()无法正常运行
问题描述:
我有如下关系定义: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方法,所有类别的帖子都在加载!
非常感谢一些帮助。无法弄清楚为什么会发生这种情况。
答
无需在关系的子查询中添加->get()
。
$cats_and_posts = Category::with([
'posts' => function ($query) {
$query->orderBy('updated_at', 'desc')
->take(3);
}
])
->withCount('posts')
->orderBy('posts_count', 'desc')
->take(3)
->get();
仍然没有解决问题!内部查询只返回一些类别的空集合! –