[英]Issue querying laravel eloquent 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()之后
你能代替$restaurants = \\App\\Restaurant::paginate(3);
并修改刀片代码说
<?php
foreach($restraunts_data as $resturant) {
if(count($restaurant->offer) {
print_r($restaurant->offer);
}
}
?>
首先,我建议将您的报价关系更改为:
public function offers()
{
return $this->hasMany(Offer::class, 'restaurant_ID', 'id');
}
上面假设Offer
类和Restaurant
类在同一名称空间中。 如果不是,请添加正确的名称空间或将Offer
模型导入到类中。
其次,由于要对结果进行分页,因此最终会得到一组Restaurant
模型(即使只有一个),因此您需要遍历它们以访问每种模型的报价。 我也建议急于加载结果,例如
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() }}
您使用的模型不正确。 您不运行查询,并且尝试在Restaurant
类上运行静态方法而不选择任何餐厅。 据我所知,这不是口才的支持。 如果您查看错误消息,它会抱怨没有属性$offer
。
尝试运行一些查询,然后选择相关的Offer
。 这应该按预期工作。
例如:
$offers = \App\Restaurant::find(1)->offer;
这将返回ID为1的Restaurant
的许多Offer
关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.