Как запросить идентификатор продавца из таблицы продуктов в базе данных Laravel - PullRequest
0 голосов
/ 14 июня 2019

Я работаю над проектом, в котором пользователи могут продавать, а также покупать продукты, и в моей базе данных есть две таблицы (таблица заказов и продуктов заказа), в таблицах заказов есть customer_id и seller_id.Таким образом, если пользователь покупает продукт, он показывает customer_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'));

My View File (blade)

  @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 голосов
/ 14 июня 2019

Существует проблема, связанная с тем, что у каждого товара должен быть продавец. В таком случае следует использовать отношения покупателя и продавца с моделью OrderProduct, а не Order. Или вы можете собрать продавца, связавшись с product-seller.

Первый

удалить 'buyer_id', 'seller_id', из Order model и orders migration.

Второй

Добавьте 'buyer_id', 'seller_id', из OrderProduct model и order_product migration.

Третий

Передаточное отношение buyer и seller от Order модели к OrderProduct модели

Четвертый

Когда вы создаете OrderProduct data, вы добавляете buyer_id и seller_id. Наконец поймайте и используйте их как хотите.

Пятый

Не забудьте обновить buys и sells отношение Order 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');
}

Обратите внимание, что вы не можете сделать их из одной функции. Наконец, обновите все, что связано с этими изменениями.

0 голосов
/ 14 июня 2019

Добавьте это к OrderProduct.php

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

Обновление продукта Controller

 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!');
     }
0 голосов
/ 14 июня 2019

Давайте посмотрим, сможем ли мы найти, возможно, самое простое решение.По вашей модели продукта видно, что у нее есть поле 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');

надеюсь, что это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...