Reputation: 1027
I have a Restaurants table and an Offers table. One restaurant may have multiple Offers. I am trying to create the relation between Restaurant - Offers using hasMany() method.
Table structure :
1) restaurant
id
restaurant name
2) offers
offer_id
restaurant_ID
offer_price
Code : In the Restaurant Model in am doing something like this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Restaurant extends Model
{
public function offer(){
return $this->hasMany('Offer');
}
}
and in view, i tried printing the result using
below code in view
foreach ($restaurants_data as $key => $value) {
print_r($value->offer);
?>
Routes code :
Route::get('/home/restaurants',function(){
$restaurants = DB::table('restaurants')->simplepaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
But i am not getting the offers data, where am i going wrong. Thanks.
Upvotes: 1
Views: 343
Reputation: 697
In the model change the code like this :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Restaurant extends Model
{
public function offer(){
return $this->hasMany('Offer','restaurant_ID','id');
}
}
Upvotes: 0
Reputation: 35337
If you want the relationships defined in the Model, you have to use the Model:
$restaurants = \App\Restaurant::simplePaginate(3);
The query builder doesn't return model instances, it returns stdClass objects.
Upvotes: 1