将数据导入belongsToMany关系Laravel

时间:2017-08-24 12:54:54

标签: php laravel eloquent

我是laravel的初学者,我希望得到一个关系ManyToMany。这是我的迁移文件:

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

由于

1 个答案:

答案 0 :(得分:4)

您可以使用:

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

参考文献: