2017-08-24 70 views
2

我是laravel的初學者,我想得到一個ManyToMany的關係。這是我的移民文件:將數據導入belongsToMany關係Laravel

public function up() 
{ 
    Schema::create('products', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name')->unique(); 
     $table->string('slug')->unique(); 
     $table->text('description'); 
     $table->decimal('price', 10, 2); 
     $table->string('image')->unique(); 
     $table->timestamps(); 
    }); 

    Schema::create('product_user', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('number')->unsigned(); 
     $table->integer('product_id')->unsigned()->index(); 
     $table->integer('user_id')->unsigned()->index(); 
     $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); 
     $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
    }); 
} 

,這是類用戶的產品類

class Product extends Model 
{ 
public $fillable = ['name', 'slug', 'description', 'price', 'image']; 

public function users() 
{ 
    return $this->belongsToMany('App\Models\User'); 
} 
} 

,我補充一點:

public function products() 
{ 
    return $this->belongsToMany('App\Models\Product'); 
} 

我的問題是如何讓外地號碼???

@foreach($user->products as $product) 
Produit : {{ $product->name }} <br/> 
Slug : {{ $product->slug }}<br/> 
Number : {{ /* how to get this ??? */ }}<br/> 
@endforeach 

感謝

回答

3

您可以使用此:

public function products() 
{ 
    return $this->belongsToMany('App\Models\Product')->withPivot('number'); 
} 

並獲得這樣的:

@foreach($user->products as $product) 
    Produit : {{ $product->name }} <br/> 
    Slug : {{ $product->slug }}<br/> 
    Number : {{ $product->pivot->number }}<br/> 
@endforeach 

參考文獻:

相關問題