gpt4 book ai didi

php - 插入多对多关系 laravel 5

转载 作者:行者123 更新时间:2023-11-28 23:19:31 24 4
gpt4 key购买 nike

我有两个模型:

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 个数据数组:$data = $request->except('_token','submit'); - 有关客户的信息$order_content - 包含购物车中产品信息的数组

那么,问题是如何将所有这些数据插入到数据库中?我试图阅读有关多对多插入的内容:同步、附加等。但一无所知:c

最佳答案

假设您有一个 ID 为 1 的产品。还有一个 ID 为 1 的订单。该产品是订单的一部分,因此您必须附加它们。你做

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

但是,在您的情况下,您的数据透视表有更多数据,例如“数量”。然后你做,

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

到目前为止,我们只将一个产品附加到订单中。如果您想同时附加许多产品,您可以:

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

我希望这有助于更好地理解。我建议您反复阅读文档,直到理解为止。

关于php - 插入多对多关系 laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com