根据选定的类别选择帖子

时间:2014-09-09 13:27:43

标签: php mysql laravel laravel-4 eloquent

我有以下情况:

  • 用户选择几个类别
  • 用户应该看到属于这些类别的帖子
  • 帖子属于一个或多个类别

我像这样设置数据库:

users -> category_user <- categories

posts -> categoriy_post <- categories

我设法完成了这项工作,但我必须从这些表中找到所有ID以查找相关帖子。我需要简化它,因为这种方法阻止了我需要做的其他一些操作。这是我的代码:

$categoryIds = Auth::user()->categories;
$ids = array();
$t = array_filter((array)$categoryIds);
if(!empty($t)){
    foreach ($categoryIds as $key => $value) {
        $ids[] = $value->id;
    }
}else{
    return View::make("main")
    ->with("posts", null)
    ->with("message", trans("front.noposts"))->with("option", "Latest");
}

$t = array_filter((array)$ids);

if(!empty($t)){
    $p = DB::table("category_post")->whereIn("category_id", $ids)->get();
}else{
    return View::make("main")
    ->with("posts", null)
    ->with("message", trans("front.noposts"))->with("option", "Latest");
}
$postsIds = array();
foreach ($p as $key => $value) {
    $postsIds[] = $value->post_id;
}

$t = array_filter((array)$postsIds);
if(!empty($t)){
    $postIds = array_unique($postsIds);
    $posts = Post::whereIn("id", $postsIds)
        ->where("published", "=", "1")
        ->where("approved", "=", "1")
        ->where("user_id", "!=", Auth::user()->id)
        ->orderBy("created_at", "desc")
        ->take(Config::get("settings.num_posts_per_page"))
        ->get();

    return View::make("main")
        ->with("posts", $posts)->with("option", "Latest");
}else{
    return View::make("main")
    ->with("posts", null)
    ->with("message", trans("front.noposts"))->with("option", "Latest");
}

如果没有这一束代码,如何正确地做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以直接从用户记录中的数据库中获取这些类别:

SELECT ... 
FROM posts AS p 
INNER JOIN category_post AS cp ON cp.id_post = p.id 
INNER JOIN categories AS c on c.id = cp.id_category 
INNER JOIN category_user AS cu ON cu.id_category = c.id 
WHERE cu.id_user = 123 AND p.published = 1 AND ...

加入Laravel可以实现,请参阅文档:laravel.com/docs/queries#joins也许还有一种雄辩的方式,我不知道,尝试搜索: - )

答案 1 :(得分:1)

是的,有雄辩的方式:

$userCategories = Auth::user()->categories()
        ->select('categories.id as id') // required to use lists on belongsToMany
        ->lists('id');

if (empty($userCategories)) // no categories, do what you need

$posts = Post::whereHas('categories', function ($q) use ($userCategories) {
   $q->whereIn('categories.id', $userCategories);
})->
   ... // your constraints here
  ->get();

if (empty($posts)) {} // no posts

return View::make() ... // with posts

这个聪明的伎俩甚至更好:

$posts = null;

Auth::user()->load(['categories.posts' => function ($q) use (&$posts) {
   $posts = $q->get();
}]);

if (empty($posts)) // no posts

return View... // with posts

显然,您可以编写joins,甚至是原始sql;)