本系列文的環境狀態,可點擊此連結後花園環境參考
本次會繼續延用 flowers_table ,不懂得看倌要問,或是可以去翻下小的之前的文章
多對多皆使用 belongsToMany 方法,在本次內容將建立的關係:
在 Terminal 輸入指令
$ php artisan make:model Buyer -m
$ php artisan make:migration create_flower_buyer_table
$ php artisan make:model FlowerBuyer
填入程式碼
主要只增加 $table->string('buyname');
這行
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBuyersTable extends Migration
{
public function up()
{
Schema::create('buyers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('buyname');
// 買家的名字
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('buyers');
}
}
填入程式碼
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFlowerBuyerTable extends Migration
{
public function up()
{
Schema::create('flower_buyer', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('flower_id');
// 參照 flowers table 的 id
$table->unsignedBigInteger('buyer_id');
// 參照 buyers table 的 id
$table->string('bunch');
// 購買的花束量
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('flower_buyer');
}
}
填完要建立的列位名,確認無誤後
到 Terminal 輸入指令,讓資料庫生成表單
$ php artisan migrate
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flower extends Model
{
public function buyers()
{
// 每種花有數的買家的紀錄,並綁定樞紐欄位
return $this->belongsToMany('App\Buyer','flower_buyer')->withPivot('bunch');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Buyer extends Model
{
protected $fillable = ['buyname'];
public function flowers()
{
// 買家的購買紀錄屬於多種花
return $this->belongsToMany('App\Flower','flower_buyer');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class FlowerBuyer extends Model
{
// 條件限制使用的 table
protected $table = 'flower_buyer';
}
參考連結:
❁ Laravel 官方 - Eloquent: Relationships
❁ PHP laravel中的多對多關係例項詳解
❁ Charllen 大 - Laravel新手基礎訓-Eloquent: Relationships-One to Many