php - 插入多对多关系 laravel 5

标签 php mysql laravel eloquent

我有两个模型:

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/

相关文章:

php - Laravel 5.7 Schema 外键 SQLSTATE[42000] 迁移

PHPMailer 在发送电子邮件时使用 Gmail SMTP 速度很慢

mysql - 如何将 ruby​​ on Rails 应用程序导入到另一台计算机

php - 在 Phonegap 项目中组合 Ajax、Jquery、mysql、php 不起作用

PHP - DynamoDB - 唯一键

php - CSS :last-child using on Laravel @foreach

php - 在 HandlerSocket 上基于原始套接字的查询中表示 NULL 键值的正确方法

php - 获取每个用户的最新 N 个帖子

php - Sentry on Laravel 4. 无密码社交认证

jquery - 如何返回登录凭据出错的选项卡