Laravel 之多對多的關係模型

13122826258發表於2019-05-11
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
      function products()
     {
          return $this->belongsToMany(Product::class, 'product_shop', 'shop_id', 'product_id')
                             ->withPivot('products_amount', 'price')->withTimestamps();
     }
}

    <?php

    namespace App\Http\Controllers;
    use App\Shop;
      class TestController extends Controller
    {
              public function index()
             {  
                      $shop_id = 1;
                      $shop = Shop::find($shop_id)->products;
                      print_r($shop);
                      $shop->products()->attach(20); //新增
                      $shop->products()->detach(20); //刪除
                      $shop->products()->detach(); //刪除全部
                      $shop->products()->attach([123, 456, 789]);//批量新增
                      $shop->products()->detach([321, 654, 987]);//批量刪除
                      $shop->products()->sync([2,7,200]); //inser   delete
                      $shop->products()->attach(1, ['products_amount' => 100, 'price' => 49.99]); //新增

                      foreach ($shop->products as $product)
                      echo $product->pivot->price;

        }
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章