Laravel Eloquent One to Many relationship

╄→гoц情女王★ 提交于 2019-12-23 03:15:39

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/46240576/laravel-eloquent-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!