K
Size: a a a
K
K
$category = Category::where('slug', $slug)->firstorFail();
$article = $category
->posts()
->where('id', '!=', $id)
->orderBy('created_at', 'DESC')
->limit(5)
->get();
AH
$category = Category::where('slug', $slug)->firstorFail();
- один запрос$article = $category->posts()
- нет with
, выполнит 5 запросов. В этом случае родительский объект не становится релейшеном. Его нужно явно указывать.$lastposts = Post::with('category')
- выполнит ещё один запрос в категории./*В этом случае должно быть всего 5 уникальных запросов: на конкретную категорию, на конкретный пост, на список постов для уже загруженной категории, четвёртый на последние посты и шестой на категории для них.
* В роутах дожно быть так:
*
* ->get('{category:slug}/{post}', 'YourController@show');
*/
public function show(Category $category, Post $post)
{
$articles = $category
->posts()
->where('id', '!=', $post->id)
->latest()
->take(5)
->get()
->map(function (Post $post) use ($category) {
return $post->setRelation('category', $category);
});
$lastposts = Post::with('category')
->where('id', '!=', $post->id)
->latest()
->take(6)
->get(['id', 'title', 'created_at', 'counter', 'category_id']);
/*$post->increment('counter');*/
return view('post.view', compact('post', 'articles', 'lastposts'));
}
AH
K
AH
AH
K
AH
->map(function (Post $post) use ($category) {Этот участок нужен для того, чтобы не делать запрос в базу на категорию, которая уже находится в переменной.
return $post->setRelation('category', $category);
});
AH
K
Route::get('{category:slug}/{post}', 'PostController@show')
->name('postshow')
->where('id', '^[0-9]+$');
K
AH
route('postshow')
?AH
AH
route('postshow', ['category' => 'foo', 'post' => 1])
AH
slug, id
, а стало category, post
AH
route('postshow', ['slug' => 'foo', 'id' => 1])
После:route('postshow', ['category' => 'foo', 'post' => 1])
K
route('postshow', ['slug' => 'foo', 'id' => 1])
После:route('postshow', ['category' => 'foo', 'post' => 1])