Как получить доступ к родительским данным eloquent join - PullRequest
0 голосов
/ 10 ноября 2019

У меня есть две таблицы Продукты и Заказы Я могу получить доступ ко всем данным в таблице Заказ , но не могу получить доступ Продукты product_name

ниже модель заказа

class Order extends Model
     {
    // Table name
     protected $tablename = 'orders';
    // primary key
     public $primaryKey = 'id';

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

Product модель

class Product extends Model
{
    // Table name
    protected $tablename = 'products';
    // primary key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;    

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

в моем контроллере у меня естьэтот OrderController

class OrdersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(){
        $orderedProducts = Order::with('products')->paginate(5);
        return view::make('orders.index')->with('products',$orderedProducts);
    }
}

теперь пытается получить доступ к product_name в представлении не удается

@foreach ($products as $product)
  <tr>
 <td>{{'#'.++$i}}</td>
 <td>{{$product->product_name}}</td> //fails to get this from products table
 <td>{{$product->quantity}}</td>
 <td>{{$product->totalPrice}}</td>
 <td>{{$product->totalPrice * $product->quantity }}</td>
 <td>{{$product->created_at->diffForHumans()}}</td>
 <td>{{$product->orderStatus}}</td>                                                                         
 </tr>
@endforeach 

Ответы [ 2 ]

0 голосов
/ 10 ноября 2019

я наконец понял, изменив мой метод модели с products на product , потому что он имел то же имя с protected $tablename = 'products'; в Модель продукта , затем после этого я ссылался на соответствующий метод Продукт в Заказ модели непосредственно в представлении, как следует <td>{{$product->product->product_name}}</td>

полный рабочий кодтеперь ниже

модель заказа , где я изменил метод с продукты на продукт

class Order extends Model
{
    // Table name
    protected $tablename = 'orders';
    // primary key
    public $primaryKey = 'id';


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

продуктмодель

class Product extends Model
{
    // Table name
    protected $tablename = 'products';
    // primary key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;    

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

Контроллер

public function index(){
        $order = Order::with('product')->paginate(5);
        return view::make('orders.index')->with('order',$order);
    }

, наконец, в представлении , где я делаю ссылку на метод product в Заказ модели

@foreach ($order as $product)
    @if (!empty($product))
     <tr>      
       <td>{{$product->product->product_name}}</td> **//Here is the referencing**
       <td>{{$product->quantity}}</td>
       <td>{{$product->totalPrice}}</td>
       <td>{{$product->totalPrice * $product->quantity }}</td>
       <td>{{$product->created_at->diffForHumans()}}</td>
       <td>{{$product->orderStatus}}</td>                                                                         
     </tr>                                                   
   @endif                                                     
@endforeach 
0 голосов
/ 10 ноября 2019

Нужно сделать это

Контроллер:

public function index(){
    $order = Order::with('products')->paginate(5);
    return view::make('orders.index')->with('products',$order->products);
}

или

Контроллер:

public function index(){
    $order = Order::with('products')->paginate(5);
    return view::make('orders.index')->with('order',$order);
}

Вид:

@foreach ($order->products as $product)
@if(!empty($product))
  <tr>
 <td>{{'#'.$loop->iteration}}</td>
 <td>{{$product->product_name}}</td> //fails to get this from products table
 <td>{{$product->quantity}}</td>
 <td>{{$product->totalPrice}}</td>
 <td>{{$product->totalPrice * $product->quantity }}</td>
 <td>{{$product->created_at->diffForHumans()}}</td>
 <td>{{$product->orderStatus}}</td>                                                                         
 </tr>
@endif 
@endforeach 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...