Laravel 之多对多的关系模型
<?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 协议》,转载必须注明作者和本文链接