这是参考这个问题:
Laravel Eloquent One to Many relationship
我尝试了建议的方式,但无法解决。请帮忙。以下是我所做的更改:
早些时候:
//Route for Restaurants Page
Route::get('/home/restaurants',function(){
$restaurants = DB::table('restaurants')->simplepaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
根据建议更改:
Route::get('/home/restaurants',function(){
// $restaurants = DB::table('restaurants')->simplepaginate(3);
$restaurants = \App\Restaurant::simplePaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
在餐厅模特
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Restaurant extends Model
{
public function offer(){
return $this->hasMany('Offer');
}
}
在视图中,现在我试图通过转储值来访问它。
<?php
var_dump($restaurants_data->offer);
?>
执行dd()
之后答案 0 :(得分:1)
你能替换吗?
$restaurants = \App\Restaurant::paginate(3);
并修改刀片代码以说明
<?php
foreach($restraunts_data as $resturant) {
if(count($restaurant->offer) {
print_r($restaurant->offer);
}
}
?>
答案 1 :(得分:1)
首先,我建议将您的优惠关系更改为:
public function offers()
{
return $this->hasMany(Offer::class, 'restaurant_ID', 'id');
}
以上假设Offer
类和Restaurant
类位于同一名称空间中。如果他们不是,请添加正确的命名空间或将Offer
模型导入到课程中。
其次,因为您要对结果进行分页,最终会得到Restaurant
个模型的集合(即使只有一个),所以您需要遍历它们才能访问每种型号的优惠。我还建议eager loading结果,例如。
Route
:
Route::get('/home/restaurants', function () {
$restaurants = \App\Restaurant::with('offers')->simplePaginate(3);
return view('restaurants', compact('restaurants'));
});
在您看来:
@foreach($restaurants as $restaurant)
@foreach($restaurant->offers as $offer)
{!! dump($offer) !!}
@endforeach
@endforeach
{{ $restaurants->links() }}
答案 2 :(得分:0)
您使用的模型不正确。您不运行任何查询,并尝试在Restaurant
类上运行静态方法而不选择任何餐馆。据我所知,这不是Eloquent支持的。如果您查看错误消息,则会抱怨没有属性$offer
。
尝试运行一些查询,然后选择相关的Offer
。这应该按预期工作。
例如:
$offers = \App\Restaurant::find(1)->offer;
这将返回ID为1的Offer
的许多Restaurant
关系。