从laravel中的数据透视表中检索数据

时间:2017-07-25 11:05:25

标签: php laravel

我是laravel的新手。我想为文章ID(1)显示类别A,B,C。但是它显示了文章id(i)的id号1,2,3。我花了几个小时才得到解决方案,但都失败了。我想知道如何正确编码。另一个问题是使用implode()将数组插入db是正确的方法。

category table
--------------------
|    id | category |
|     1 |   A      |
|     2 |   B      |
|     3 |   C      |
|     4 |   D      |
|     5 |   E      |
--------------------

article_category ( pivot table )
----------------------------
| article_id | category_id |
|     1      |      1      |
|     1      |      2      |
|     1      |      3      |
|     2      |      1      |
|     2      |      5      |
----------------------------

HTML

@foreach( $categories as $category )
    <input type="checkbox" name="category[]" value="{{ $category->id }}" checked>&nbsp;{{ $category->category }}&nbsp;&nbsp;
@endforeach

Laravel Store

public function store(Request $request)

{
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:articles|max:255',
        'content' => 'required',
        'category' => 'required|max:100',
        'status' => 'required|max:1'
    ]);

    if( $validator->passes() )  
    {
        $category = implode(',', $request->category);
        $articles = Article::create([
            'title' => $request->title,
            'content' => $request->content,
            'category' => $category,
            'status' => $request->status,
        ]);

        $articles->categories()->sync($request->category);

        return redirect($this->redirectTo)
                ->with($this->key, $request->title.$this->storeSuccess);
    }
    else 
    {
        return redirect($this->redirectTo.'/create')
                ->withInput($request->all())
                ->withErrors($validator);
    }
}

1 个答案:

答案 0 :(得分:0)

首先你必须在文章模型中定义一个关系,如此

public function categories(){
    return $this->belongsToMany('ModelNameWithNamespace');
}

比你可以访问它

$categories = $article->category;
foreach($categories as $category)
{
    echo $category->{your field name};
}

此外,您应该以相同的方式指定从类别到文章的关系