【问题标题】:How does the eloquent pivot consult are written?雄辩的枢轴咨询是如何编写的?
【发布时间】:2020-06-28 18:30:33
【问题描述】:

我正在开发一个电子商务。问题是我在user 模型中为购物车创建了一个函数belongsToMany 来保存许多产品,称为carrito。但是在控制器中,当我想获得产品的id 时,给我一个错误,好像属性不存在一样。我想做的是从现有表carts(使用函数carrito)中获取数据并将其插入一个名为pedidos的新表中

这里是代码...

模型:用户

public function carrito(){
    return $this->belongsToMany(Product::class, 'cart')
                ->withPivot('product_id', 'user_id', 'quantity');

}

控制器

public function create(Request $request)
{
    $user =Auth::user();
    $producto = $user->carrito;    

    Pedido::create([
        'user_id'=>Auth::User()->id,
        'puntosretiros_id' => $request->get('puntoE'),
        'product_id' => $producto->product_id,
        'quantity' => $producto->quantity,
        'total'=> $request->input('total'),
    ]);    
    $pedido->save();
    return redirect('/');
}

【问题讨论】:

  • 关系中提到的表名(cart)与您所说的不同(carts
  • $producto = $user->carrito; 将返回记录集合。所以你将无法访问这样的值,$producto->product_id
  • 如果您需要将关系中的所有记录插入到新记录中,则循环通过$producto->product_id 并创建一个数据数组,然后将该数据插入到表中

标签: laravel eloquent eloquent-relationship


【解决方案1】:

如果您需要一些建议,我建议您进行一些细微的更改以使您的代码更清晰:


1) 模型

用户

User 有一个Cart

/**
 * A User has a cart.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasOne
 */
public function cart()
{
    return $this->hasOne(Cart::class);
}

购物车

Cart 属于 User

一个Cart 有很多Products

/**
 * A Cart belongs to a User.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function cart()
{
    return $this->belongsTo(User::class);
}

/**
 * A Cart has many Products.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function products()
{
    return $this->belongsToMany(Product::class)->withPivot(['quantity']);
}

一个Product 可以是多个Carts

/**
 * A Product can be in many Carts.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function products()
{
    return $this->belongsToMany(Cart::class)->withPivot(['quantity']);
}

2) 关系

通过这种方式配置您的模型,您现在可以像这样访问您的数据;

// Load a user with all their carts and products
$user = User::with(['carts.products])->find(1);

// Get a specfic cart
$cart = $user->carts->first();

// Get the products in their cart
$products = $cart->products;

// Get quantity of the first product in the cart
$quantity = $products->first()->pivot->quantity;

现在所有这些只是一个基本示例,但演示了您可以使用一些关系和Pivot 模型和属性来做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2020-10-26
    • 2018-07-05
    相关资源
    最近更新 更多