2015-10-08 71 views
1

的拆分内容我有这样mysql表:Laravel 5.1 - 表

+----+-------------------------------+---------+--------------+-------------+ 
| id |    title    | chapter | date_release | author | 
+----+-------------------------------+---------+--------------+-------------+ 
| 1 | This is should be title One |  1 | 10/08/2015 | John Robert | 
| 2 | This is should be title Two |  1 | 11/08/2015 | John Robert | 
| 3 | This is should be title Three |  1 | 12/08/2015 | John Robert | 
| 4 | This is should be title Four |  2 | 10/09/2015 | Sir Arthur | 
| 5 | This is should be title Five |  2 | 11/09/2015 | Sir Arthur | 
| 6 | This is should be title Six |  1 | 13/08/2015 | John Robert | 
| 7 | This is should be title Seven |  2 | 12/08/2015 | Sir Arthur | 
+----+-------------------------------+---------+--------------+-------------+ 

在Laravel 5.1我想从基于chapter表分裂,并导致view这样的:

<div class="chapter-1"> 
    <span> 
    ... 
    All content from table of chapter 1 only 
    ... 
    </span> 
</div> 
<div class="chapter-2"> 
    <span> 
    ... 
    All content from table of chapter 2 only 
    ... 
    </span> 
</div> 

我有不知道我应该在controller中做什么查询功能,以及如何在laravel view中显示它?

编辑:

@ aldrin27问我关于我的控制器,在这儿呢。

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 
use App\Book; 
use App\Http\Requests; 
use App\Http\Controllers\Controller; 

class BookController extends Controller { 

    ... 
    ... 


    public function show($id) { 
     // 
     $book = Book::find($id); 
     return view('books.show', compact('book')); 
    } 

    ... 
    ... 

} 
+0

我可以看到你的控制器吗? – aldrin27

+0

我的'controller'是一个标准的Laravel控制器,它有'index','edit','show','store'等。如果我不知道如何做到这一点,我应该如何显示我的控制器功能? (仍为空控制器) – wahyueka31

+0

什么控制器会查询您的数据并将其传递给视图? – aldrin27

回答

0

Book::find($id)只会返回一个模型。你想要的是让模型的Collection工作(例如:分裂,分组等)。改为使用all()get()

例如,不要在你的控制器如下:

$books = Book::all(); 

$groupedBooks = $books->groupBy('chapter'); 

通行证$groupedBooks到您的视图,并做一些像在您的视图文件中的以下内容:

@foreach($groupedBooks as $chapter => $books) 
    <div class="chapter-{{ $chapter }}"> 
     @foreach($books as $book) 
      <p>{{ $book->title }}</p> 
     @endforeach 
    </div> 
@endforeach 

注:我觉得有一个问题与你如何建立你的关系。例如,Book包含(零个或多个?)Chapter,因此这些将是两个相关模型,而不是仅使用一个模型 - Book。但那只是我...