如何显示具有与表单输入匹配的特定类别的文章 - Laravel

时间:2015-12-06 00:29:57

标签: php mysql laravel-5.1

我无法根据类别限制搜索/显示结果。

我有很多关系。一篇文章有​​很多类别,一个类别有很多文章。用户在表单中输入地址并选择1-3个类别。然后,我希望将这些用户指定的类别与我的数据库中包含这些类别的文章进行匹配,并仅显示这些特定文章。

我一直在寻找像THIS ONE这样的许多SO问题,似乎无法让事情发挥作用。我的主要错误是我得到$ categories的未定义属性。

在我添加类别之前,它正在工作,我可以显示一定距离内的文章列表。我正在使用Laravel 5.1。

数据库表: “文章” (id,title等...) “类别” (id,name) 'article_category' (article_id,category_id)

这是我的代码:

文章模型:

    public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }

public function getCategoryListAttribute()
    {
        return $this->categories->lists('id')->all();
    }

类别模型:

    public function articles()
{
    return $this->belongsToMany('App\Article')->withTimestamps();
}

文章控制器

public function index(Request $request)
    {

    $lat = $request->get('lat');
    $lng = $request->get('lng');
<--! THIS GETS THE USER DEFINED CATEGORY CHOICES -->
    $categoryChoice = $request->get('categoryList');
    $distance = 1;

    $query = Article::getByDistance($lat, $lng, $distance);

        if(empty($query)) {
        return redirect()->action('HomeController@index');
        }

        $ids = [];

        //Extracts the alticle/store id's
        foreach($query as $q)
        {
          array_push($ids, $q->id);
        }

<--! Get the listings that match the returned ids -->
        $results = DB::table('articles')
        ->whereIn( 'id', $ids)
        ->orderBy('title', 'DESC')
        ->paginate(6);   

       $articles = $results; 

<--! THIS IS TO GET CATEGORY IDS OF NEARBY STORES - NOT WORKING ->
        $categoryMatches = [];

        foreach ($articles->categories as $category){

            array_push($categoryMatches, $category->pivot->category_id);

        }

<--! THIS WILL IDENTIFY WHETHER THE CATEGORIES OF NEARBY STORES MATCH THE CATEGORIES CHOSEN IN THE FORM - NOT WORKING -->
        $articles = $articles->whereIn($categoryMatches, $categoryChoice);

        return view('articles.index', compact('categories', 'days'))->withArticles($articles);

    }

1 个答案:

答案 0 :(得分:0)

您的查询会返回文章集。您需要先对文章进行迭代,因为每篇文章都有很多类别。

[
  {
    "username": "lovelyday", 
    "email": "lovelyday@gmail.com"
  }, 
  {
    "username": "what", 
    "email": "whoknows@nothing.com"
  }
]