2015-10-08 94 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。但那只是我...