[英]get data into belongsToMany relation Laravel
I am a beginner in laravel, I want to get a relation ManyToMany. 我是laravel的初学者,我想建立一个ManyToMany关系。 This is my migration file:
这是我的迁移文件:
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');
});
}
and This is the product class 这是产品类别
class Product extends Model
{
public $fillable = ['name', 'slug', 'description', 'price', 'image'];
public function users()
{
return $this->belongsToMany('App\Models\User');
}
}
in class user, i add this : 在班级用户中,我添加以下内容:
public function products()
{
return $this->belongsToMany('App\Models\Product');
}
My problem is how to get the field number ??? 我的问题是如何获取字段号?
@foreach($user->products as $product)
Produit : {{ $product->name }} <br/>
Slug : {{ $product->slug }}<br/>
Number : {{ /* how to get this ??? */ }}<br/>
@endforeach
Thanks 谢谢
You can use this: 您可以使用此:
public function products()
{
return $this->belongsToMany('App\Models\Product')->withPivot('number');
}
and access like this: 并像这样访问:
@foreach($user->products as $product)
Produit : {{ $product->name }} <br/>
Slug : {{ $product->slug }}<br/>
Number : {{ $product->pivot->number }}<br/>
@endforeach
References: 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.