dsjmrpym220113739 2018-03-26 20:03
浏览 55
已采纳

如何将信息插入Order-OrderProduct表MySQL Laravel

I am developing simple e commerce website with laravel for learning purposes.

There are few things confusing me about database relations and inserting data to order-order_product tables when customer places an order.

User Migration:

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

User Model:

class User extends Authenticatable
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $attributes =[
     'street' => 'no adress entered',
     'city' => 'no city entered',
     'phone' => 'no phone'


    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function orderproduct(){        
        return $this->hasMany('App\OrderProduct');   
}
}

Orders Table:

 Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('customer_id')->unsigned();
            $table->foreign('customer_id')->references('id')->on('users');
            $table->string('name');
            $table->string('address');
            $table->string('phone');
            $table->date('order_date'); 

            $table->timestamps();
        });

Order Model:

class Order extends Model
{
   //Table Name

   protected $table = 'orders';

   //Primary Key

   public $primaryKey = 'id';

   //Timestamps

   public $timestamps =true;

public function user(){        
        return $this->belongsTo('App\User');   
}

public function orderproduct(){
    return $this->hasMany('App\OrderProduct');
}

}

Products Table:

Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('img');
            $table->string('name');
            $table->string('desc');
            $table->integer('quantity');//stokta kaç tane oldugu
            $table->integer('price');
            $table->timestamps();
        });

Product Model:

    class Product extends Model
{

    //Table Name

    protected $table = 'products';

    //Primary Key

    public $primaryKey = 'id';


    //Timestamps

    public $timestamps =true;

    public function orderproduct(){        
        return $this->belongsTo('App\OrderProduct');

    }
}

order_product Table:

 Schema::create('order_product', function (Blueprint $table) {
            $table->increments('id');
              $table->integer('order_id')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->integer('quantity')->unsigned();
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders');
            $table->foreign('product_id')->references('id')->on('products');
        });

OrderProduct Model:

class OrderProduct extends Model
{

    //Table Name

    protected $table = 'order_product';

    //Primary Key

    public $primaryKey = 'id';


    //Timestamps

    public $timestamps =true;

public function order(){         
    return $this->belongsTo('App\Order');   

}
public function product(){
    return $this->hasMany('App\Product');   

}



}

I am using laravel session to hold cart data.Also i have a ordercontroller for storing order to database. The question is how do i insert correctly to order and order_product tables? First am i going to insert to orders then to order_product table ? For example if user has multiple items in his cart because product_id column in order_product table needs to be atomic i need to insert multiple rows. I can access product_id and their quantity from my cart but i couldnt manage to loop them properly and insert to db.

public function store(Request $request)
    {
        $oldCart = Session::get('cart'); 
        $cart = new Cart($oldCart);
//dd(arrays_keys($cart->items)); // returns ids of products in cart
//dd($cart->items[1]['qty']);      // returns quantity of item which has id 1



        $order = new Order;
        $order->name = $request->input('name');
        $order->address = $request->input('address');
        $order->phone = $request->input('phone');
        $order->customer_id = auth()->user()->id;

        $order->save();

        $orderProduct = new OrderProduct;

        //$orderProduct->product_id = ??  how to write in multiple rows if user has multiple items(so values will be atomic in product_id column)
        //$orderProduct->quantity= ??



    }
  • 写回答

1条回答 默认 最新

  • dsag14654 2018-03-26 22:16
    关注

    Wrap them in transaction and insert them as usual:

    DB::transaction(function() use($request) {
    
        $oldCart = Session::get('cart'); 
        $cart = new Cart($oldCart);
    
        $order = new Order;
        $order->name = $request->input('name');
        $order->address = $request->input('address');
        $order->phone = $request->input('phone');
        $order->customer_id = auth()->user()->id;
        $order->save();
    
        $orderProducts = [];
        foreach ($cart->items as $productId => $item) {
            $orderProducts[] = [
                'order_id' => $order->id,
                'product_id' => $productId
                'quantity' => $item['qty']
            ];
        }
        OrderProduct::insert($orderProducts);
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿