Trong website chúng ta hay hiện thị các bài viết liên quan về một bài viết hiện tại người dùng đang xem. Nay mình chia sẻ với mọi người cách mình lấy bài viết liên quan như sau:
Ở đây mình dùng Laravel, với mô hình quan hệ Post ManyToMany Category, nên sẽ lấy hơi khác xíu với mô hình Post hasMany với Category nghe
public function morePost($id,$categories) {
$listCategories = $categories->modelKeys();
$relatedPosts = \App\Models\Post::with('categories')
->whereHas('categories', function ($q) use ($listCategories) {
$q->whereIn('categories.id', $listCategories);
})
->take(8)
->where('id', '<>', $id)
->OrderBy('id', 'DESC')
->get();
return $relatedPosts;
}
Hàm morePost($id, $categories) nhận vào 2 tham số:
$id : đây là $post->id , chúng ta lấy từ post hiện tại
$categories : đây là $categories của Post hiện tại .
$post = \App\Models\Post::with('categories')->where('id', $id)->orWhere('slug', $id)->first();
$categories = $post ->categories->modelKeys();
Chúng ta sử dụng modelKeys() giúp lấy các giá trị khóa chính của bảng categories nhé hay bạn cũng có thể dùng pluck("id") để lấy ra nghe
Okay, Còn khúc sau mọi người cách dễ hình dùng rồi, chúng ta chỉ việc lấy số post khác với $id hiện tại của bài post
Nếu bạn đang dùng API Resource trả data về cho Client chúng ta có thể viết nó trong file PostResource cho dễ quản lý nhé
Code ví dụ:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
class PostResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
// return parent::toArray($request);
return [
'id' => $this->id,
'keyword' => $this->keyword,
'title' => $this->title,
'router' => $request->route()->named('posts.show'),
'user' => $request->user(),
// Kiếm tra điều kiện nếu $request là "posts.show" thi chiều hiện thị thuộc tính "image"
'image' => $this->when(
$request->route()->named('posts.show'),
$this->image
),
// Nếu user có quyền "admin.posts.show" thì ta cho hiện thị thuộc tính "content"
'content' => $this->when(
Auth::guard('api')->user()?->can('admin.posts.show'),
$this->content
),
'categories' => new CategoryResource($this->whenLoaded('categories')),
'morePost' => $this->morePost($this->id,$this->categories)
];
}
public function morePost($id,$categories) {
$listCategories = $categories->modelKeys();
$relatedPosts = \App\Models\Post::with('categories')
->whereHas('categories', function ($q) use ($listCategories) {
$q->whereIn('categories.id', $listCategories);
})
->take(8)
->where('id', '<>', $id)
->OrderBy('id', 'DESC')
->get();
return $relatedPosts;
}
}
Okay chỉ vậy thôi, ae nào thấy hửu ích, để lại một cú click chuột vào quảng cáo trên website của mình là được nhé. thank mấy đạo hửu