2017-02-24 165 views
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

回答

0

想象一下,您有一个id为1的产品和一个id为1的订单。该产品是订单的一部分,所以你必须附上它们。你做

$product = Product::find(1); 
$order = Order::find(1); 
$order->products()->attach($order->id); 

但是,在你的情况,你的数据透视表有更多的数据,如'qty'。那么你呢,

$order->product()->attach($order->id, ['qty' => 2]); 

到目前为止,我们只附加一个产品的订单。如果你想同时附加许多产品,你需要:

$order->products()->sync([ 
    $product->id => ['qty' => 1], 
    $product2->id => ['qty' => 3] 
]); 

我希望这有助于更好地理解。我建议你一遍又一遍地阅读文档,直到它有意义。

+0

它的奇怪,但在order_product即时只获得最后的产品3在订单 – Batmannn

+0

这就是即时通讯: $ 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

+0

谢谢!在你解释和阅读文档后,我已经掌握了它!这里的工作版本: foreach($ order_content as $ order_item) { $ order-> products() - > attach($ order_item ['product_id'],['qty'=> $ order_item ['qty'], '价格'=> $ order_item [ '价格']]); } – Batmannn