【发布时间】:2020-03-15 11:56:32
【问题描述】:
我正在开发一个图书馆应用程序,我想创建一个函数,用户可以在其中向客户借书。所以我有 2 个表,books 和 readers,我还创建了一个名为 book_reader 的数据透视表来创建结帐方法。但是,我在显示该表中的数据时遇到了一些问题。我已经阅读了几篇关于此的文章,但他们没有考虑到数据透视表中有一些包含新信息的数据,而不仅仅是两个表的连接。如果有人能帮助我如何显示这些数据,我将不胜感激。
型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $fillable = ['title', 'year', 'language_id', 'isbn', 'pages', 'user_id'];
public function readers()
{
return $this
->belongsToMany(Reader::class, 'book_reader')
->using(Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Reader extends Model
{
protected $fillable = ['name', 'email', 'employee_number'];
public function books()
{
return $this
->belongsToMany(Book::class, 'book_reader')
->using(Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Checkout extends Pivot
{
$table = "book_reader";
$dates = [
"maxreturndate",
"returndate",
];
}
迁移:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCheckedOutsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('book_reader', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->bigInteger('reader_id')->unsigned();
$table->foreign('reader_id')->references('id')->on('readers')->onDelete('cascade');
$table->date('maxreturndate');
$table->date('returndate')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('book_reader');
}
}
CheckedOutController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use App\Reader;
use Illuminate\Support\Carbon;
class CheckedOutController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$books = Book::doesntHave("readers")->get();
$readers = Reader::all();
return view('checkedouts/index', compact('books','readers'));
}
index.blade.php:
@foreach($readers->books as $book)
<tr>
<td>{{$book->pivot->id}}</td>
<td>{{$book->pivot->title}}</td>
<td>{{$book->pivot->name}}</td>
<td>{{$book->pivot->created_at}}</td>
<td >{{$book->pivot->maxreturndate}}</td>
<td>{{$book->pivot->returndate}}</td>
<td></td>
【问题讨论】:
标签: php mysql laravel eloquent