Заказы, размещенные покупателем, не отображаются продавцам Laravel - PullRequest
1 голос
/ 14 июня 2019

Я пытаюсь, чтобы заказы, размещенные покупателями, были видны соответствующему продавцу, но он ничего не показывает.

Я часами пытался решить эту проблему, но все еще застрял.

Это моя модель Order.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    //protected $table = 'orders';
    protected $fillable =  [
        'user_id', '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');
    }
}

Это мой OrderProduct.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

Этоmy User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

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 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()
    {
        $this->hasManyThrough(Order::class, Products_model::class, 'user_id', 'product_id');
    }
}

И, наконец, вот моя функция viewOrder в ProductController

//Orders View Function
public function viewOrders(User $user)
{
    $products = Products_model::where('user_id', '=', $user->id)->get();
    $orders = [];
    foreach($products as $product){
        array_merge($orders, $product->order);
    }
    //dd( $products);
    return view('orders')->with(compact('orders'));
}

Мне нужен каждый продавец (пользователь)кто перечислил товар для получения заказа при покупке другого покупателя (пользователя).пока он показывает "Идентификатор заказа Дата заказа Имя клиента Город клиента Телефон клиента

1 Ответ

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

В модели заказа у вас есть связь с пользователем, что означает, что у вас есть информация о покупателе. Но Вы не имеете никакого отношения к продавцу.

Поэтому добавьте отношение к продавцу.

примечание: я предполагаю, что покупатель и продавец User

Вы должны добавить отношение для покупателя и отношение для продавца (не забудьте также добавить их в базу данных. Это означает, что вам нужно добавить поле buyer_id и seller_id в orders table).

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
     //protected $table = 'orders';
     protected $fillable =  [
        'buyer_id', 'seller_id', 'shipping_email', 'shipping_name', 'shipping_city',    'shipping_phone', 'billing_subtotal', 'billing_total',
     ];    


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

     public function orders(){
          return $this->hasMany('App\OrderProduct', 'order_id');
     }
     public function buyer()
     {
         return $this->belongsTo(User::class, 'id', 'buyer_id');
     }

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

Добавьте эти два отношения в модель User. так что вы можете позвонить им легко.

 public function buys() {
    $this->hasMany(Order::class, 'buyer_id', 'id');
 }
 public function sells() {
     $this->hasMany(Order::class, 'seller_id', 'id');
 }

// Функция просмотра заказов

public function viewOrders(User $user) {
    $products = Products_model::where('user_id', '=', $user->id)->get();
    // all sells
    $sells = $user->sells;
    // all buys
    $buys = $user->buys;

}

Видно, вы можете зациклить его, как,

@foreach($sells as $sell) 
    {{ $sell->orders }} //for orders.
    {{ $sell->products }} //for product
    @foreach($sell->orders as $order)
        {{ $order->product }} //single product
    @endforeach
@endforeach
...