samedi 9 novembre 2019

How to access the parent data eloquent join

i have two tables products and orders i am able to access all data in the table Order but can't access products product_name

below is the Order model

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

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

Product model

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');
     }
}

in my controller i have this 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);
    }
}

now trying to access the product_name on the view fails

@foreach ($products as $product)
  <tr>
 <td>#</td>
 <td></td> //fails to get this from products table
 <td></td>
 <td></td>
 <td></td>
 <td></td>
 <td></td>                                                                         
 </tr>
@endforeach 


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire