Laravel雄辩的一对多关系 [英] Laravel Eloquent One to Many relationship
问题描述
我有一个餐厅"表和一个优惠"表.一间餐厅可能有多个优惠.我正在尝试使用hasMany()方法在Restaurant-Offers之间创建关系.
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.
表结构:
1)餐厅
-
id
id
餐厅名称
2)报价
-
offer_id
offer_id
restaurant_ID
restaurant_ID
优惠价格
代码:在餐厅模型中,我正在做类似的事情
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');
}
}
鉴于此,我尝试使用
视图下方的代码
foreach ($restaurants_data as $key => $value) {
print_r($value->offer);
?>
路线代码:
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.
推荐答案
如果要在模型中定义关系,则必须使用模型:
If you want the relationships defined in the Model, you have to use the Model:
$restaurants = \App\Restaurant::simplePaginate(3);
查询生成器不返回模型实例,而是返回stdClass对象.
The query builder doesn't return model instances, it returns stdClass objects.
这篇关于Laravel雄辩的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!