0
我有2种型号:插入在多对多关系laravel 5
class Order extends Model
{
protected $fillable = ['user_id','name','surname','fathers_name','phone_number','city','post_office','comment'];
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->belongsToMany('App\Product', 'order_product');
}
}
class Product extends Model
{
public function order()
{
return $this->belongsToMany('App\Order', 'order_product');
}
public function category()
{
return $this->belongsTo('App\Category');
}
}
3个表:数据的
product:
id
name
...
order_product:
id
order_id
prod_id
qty
...
order
id
city
phone
...
和2数组: $数据= $除了( '_标记', '提交')请求 - >; - 有关客户端的信息 $ order_content - 有关购物车中产品信息的数组
所以,问题是如何在数据库中插入所有这些数据?我尝试阅读许多到多个插入:同步,附加等等,但没有任何理解:c
它的奇怪,但在order_product即时只获得最后的产品3在订单 – Batmannn
这就是即时通讯: $ order =(new Order) - > create($ data); $ cart_content = Cart :: content(); $ order_content = []; foreach($ cart_content as $ key => $ cart_item){ $ order_content [$ key] ['id'] = $ cart_item-> id; $ order_content [$ key] ['qty'] = $ cart_item-> qty; } 的foreach($ order_content为$ order_item) { $命令 - >制品() - >同步([ $ order_item [ 'ID'] => [ '数量'=> $ order_item ['数量']] ]); } – Batmannn
谢谢!在你解释和阅读文档后,我已经掌握了它!这里的工作版本: foreach($ order_content as $ order_item) { $ order-> products() - > attach($ order_item ['product_id'],['qty'=> $ order_item ['qty'], '价格'=> $ order_item [ '价格']]); } – Batmannn