Laravel 5.2 installed using composer. I have 2 tables customers with id and name also orders with id, customer_id and name. Created 2 model Customer and Order. Order model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
//
protected $table = 'orders';
public function customer(){
return $this->belongsTo('App\Customer');
}
}
in the root file
Route::get('orders',function(){
$orders=App\Order::find(1);
echo "<pre>";
foreach($orders as $order){
echo $order->name."Order by ".$order->customer->name."<br />";
}
});
It show error Trying to get property of non-object
You are not adding customer entries in your function. To do so do the following:
Route::get('orders',function(){
$orders=App\Order::find(1)->customer();// this will add customer entries to your order
echo "<pre>";
foreach($orders as $order){
echo $order->name."Order by ".$order->customer->name."<br />";
}
});
Route::get('orders',function(){
$orders=App\Order::with('customer')->all()->get();// add with()
echo "<pre>";
foreach($orders as $order){
echo $order->name."Order by ".$order->customer->name."<br />";
}
});
Jest install composer using
composer install
in composer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.