如何从数据库Laravel的Products表中查询卖方ID

时间:2019-06-14 15:06:50

标签: php laravel laravel-5 eloquent

我正在研究一个项目,用户可以在该项目中出售和购买产品,并且在我的数据库中,有两个表(orders和order products表),orders表中有Buyer_id和Seller_id。因此,如果用户购买产品,则现在显示buyer_id,问题出在seller_id上。它没有显示Seller_id。

这是我的代码。

User.php

 class User extends Authenticatable
{
use Notifiable;

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

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
 protected $hidden = [
    'password', 'remember_token', 
  ];

//public function isSeller() {
 //   return $this->seller;
//}

 public function products()
 {
  return $this->hasMany(Products_model::class);
 }
/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
 ];

 public function orders()
 {
   return $this->hasManyThrough(Order::class, Products_model::class, 'buyer_id', 'seller_id', 'product_id');
  }

 public function orderFromBuyers()
 {
  $this->hasManyThrough(OrderProduct::class, Products_model::class, 'buyer_id', 'product_id');
 }

 public function orderFromSellers()
 {
    $this->hasManyThrough(OrderProduct::class, Products_model::class, 'seller_id', 'product_id');
 }
 }

Products_model.php

 <?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class products_model extends Model
{
protected $table='products';
protected $primaryKey='id';
protected $fillable= ['seller_id','pro_name','pro_price','pro_info','image','stock','category_id'];
}

OrderProduct.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class OrderProduct extends Model
{
protected $table = 'order_product';
protected $fillable = ['order_id', 'buyer_id', 'seller_id','product_id', 'quantity'];

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

public function buyer()
{
    return $this->belongsTo(User::class, 'id', 'buyer_id');
}

public function seller()
 {
    return $this->belongsTo(User::class, 'id', 'seller_id');
 }
  }

Order.php

 <?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Order extends Model
 {
//protected $table = 'orders';
protected $fillable =  [
    'shipping_email', 'shipping_name', 'shipping_city', 'shipping_phone', 'billing_subtotal', 'billing_total',
];

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

public function products()
{
    return $this->belongsToMany('App\Products_model')->withPivot('quantity');
}

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

我的商店功能

  public function store(Request $request)
   {
    //Insert into orders table
    $order = Order::create([
        'buyer_id' => auth()->user() ? auth()->user()->id : null,
        'shipping_email' => $request->email,
        'shipping_name' => $request->name,
        'shipping_city' => $request->city,
        'shipping_phone' => $request->phone,
       // 'error' => null,
    ]);

    //Insert into order product table
    if ($order) {
        foreach(session('cart')  as $productId =>$item) {
           if (empty($item)) {
               continue;
           }
           OrderProduct::create([
            'order_id' => $order->id ?? null,
            'product_id' => $productId,
           // $products=DB::table('products')->where('id',$id)->get();
            'quantity' => $item['quantity'],
            //dd($item)
        ]);
       }
    }

CheckoutController(函数)

    public function store(Request $request)
     {
    //Insert into orders table
    $order = Order::create([
        'buyer_id' => auth()->user() ? auth()->user()->id : null,
        'seller_id' => auth()->user() ? auth()->user()->id : null,            'shipping_email' => $request->email,
        'shipping_name' => $request->name,
        'shipping_city' => $request->city,
        'shipping_phone' => $request->phone,
       // 'error' => null,
    ]);

    //Insert into order product table
    if ($order) {
        foreach(session('cart')  as $productId =>$item) {
           if (empty($item)) {
               continue;
           }
           OrderProduct::create([
            'order_id' => $order->id ?? null,
            'product_id' => $productId,
           // $products=DB::table('products')->where('id',$id)->get();
            'quantity' => $item['quantity'],
            //dd($item)
        ]);
       }
    }

   //Empty Cart After  order created
    $cart = session()->remove('cart');
     return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
     }

ProductController(函数)

    public function viewOrders(User $user)
  {

        $products = Products_model::where('seller_id', '=', $user->id)->get();
        // all sells
        $sells = $user->sells;
        // all buys
        $buys = $user->buys;

    }
    //dd( $products);
    return view('orders')->with(compact('orders'));

我的查看文件(刀片)

  @foreach($sells as $sell) 
<tr>
  <td>{{$sell->orders}}</td>
  <td>{{$sell->products}}</td>
  @foreach($sell->orders as $order)
  <td>{{$order->created_at}}</td>
  <td>{{$order->shipping_name}}</td>
  <td>{{$order->shipping_city}}</td>
  <td>{{$order->shipping_phone}}</td>
  <td>
    <a href="">View Order Details</a>
  </td>
</tr>
@endforeach
@endforeach

3 个答案:

答案 0 :(得分:0)

让我们看看是否可以找到最简单的解决方案。从您的产品模型中可以看到它有一个seller_id字段。当您遍历产品以显示它们时,为什么不使用值为seller_id的隐藏输入呢?即

@foreach ( $products as $product )
  <form> // assuming you will be creating a form for the buy button
     <input type="hidden" value={{ $product->seller_id }} />
     <button type="submit">Buy Now</button>
  </form>
@endforeach

现在在您的控制器中,您将以

的身份访问Seller_id
$seller_id = request('seller_id');

希望有帮助

答案 1 :(得分:0)

存在一个问题,每个产品必须有一个卖方。如果是这样,您应该使用OrderProduct模型而非Order模型的买卖关系。 或者,您可以通过与product-seller建立联系来收集卖家。

  

第一

'buyer_id', 'seller_id',Order model中删除orders migration

  

第二

'buyer_id', 'seller_id',OrderProduct model中添加order_product migration

  

第三

将关系buyersellerOrder模型转移到OrderProduct模型

  

第四

创建OrderProduct data时,将添加buyer_idseller_id。最后,根据需要捕获并使用它们。

  

第五

别忘了将buys上的sellsOrder model关系OrderProduct model更新为User model.

  

第六次

您必须更新用户模型上的订单关系。应该是

public function orderFromBuyers()
{
    $this->hasManyThrough(OrderProduct::class, Products_model::class, 'buyer_id', 'product_id');
}
and 
public function orderFromSellers()
{
    $this->hasManyThrough(OrderProduct::class, Products_model::class, 'seller_id', 'product_id');
}

请注意,您不能通过一项功能来制作它们。 最后,更新与这些更改相关的任何其他内容。

答案 2 :(得分:0)

将此添加到OrderProduct.php

public function order()
{
    return $this->belongsTo(Order::class);
}

更新产品控制器

 public function viewOrders(User $user)
  {

      // $products = Products_model::where('seller_id', '=', $user->id)->get();
      // all sells
      $sells = $user->orderFromSellers;
      return view('orders')->with(compact('sells'));

  }
  //dd( $products);

将您的视图更新为

 @foreach($sells as $sell) 
    <tr>
        <td>{{$sell->orders}}</td>
        <td>{{$sell->products}}</td>
        <td>{{$sell->created_at}}</td>
        <td>{{$sell->order->shipping_name}}</td>
        <td>{{$sell->order->shipping_city}}</td>
        <td>{{$sell->order->shipping_phone}}</td>
        <td>
            <a href="">View Order Details</a>
        </td>
    </tr>
@endforeach

在CheckoutController(存储)上更新为

public function store(Request $request)
     {
    //Insert into orders table
    $order = Order::create([          
        'shipping_email' => $request->email,
        'shipping_name' => $request->name,
        'shipping_city' => $request->city,
        'shipping_phone' => $request->phone,
       // 'error' => null,
    ]);

//Insert into order product table
if ($order) {
    foreach(session('cart')  as $productId =>$item) {
       if (empty($item)) {
           continue;
       }
       OrderProduct::create([
        'buyer_id' => auth()->user() ? auth()->user()->id : null,
        'seller_id' => $products=DB::table('products')->find('productId')? $products=DB::table('products')->find('productId')->seller_id : null,  
        'order_id' => $order->id ?? null,
        'product_id' => $productId,
       // $products=DB::table('products')->where('id',$id)->get();
        'quantity' => $item['quantity'],
        //dd($item)
    ]);
   }
}

   //Empty Cart After  order created
    $cart = session()->remove('cart');
     return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
     }