问题查询laravel雄辩的关系 [英] Issue querying laravel eloquent relationship

查看:104
本文介绍了问题查询laravel雄辩的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于这个问题的参考:

This is with reference to this question :

Laravel雄辩的一对多关系

我尝试了建议的方法,但无法解决.请帮忙.以下是我所做的更改:

I tried the suggested way, but couldn't resolve. Please help. Below is the changes i have done :

更早:

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

在视图中,现在我正在尝试通过转储值来访问它.

In view, now I am trying to access it by dumping the values.

 <?php
    var_dump($restaurants_data->offer);

    ?>

错误:

做完dd()

推荐答案

首先,我建议将您的报价关系更改为:

Firstly, I would suggest changing your Offer Relationship to:

public function offers()
{
    return $this->hasMany(Offer::class, 'restaurant_ID', 'id');
}

以上假设Offer类和Restaurant类在同一名称空间中.如果不是,请添加正确的名称空间或将Offer模型导入到该类中.

The above assumes that the Offer class and Restaurant class are in the same namespace. If they're not please add the correct namespace or import the Offer model in to the class.

第二,由于要对结果进行分页,因此最终会得到Restaurant模型的集合(即使只有一个),因此您将需要遍历它们以访问每种模型的报价.我还建议急于加载例如结果

Secondly, because you're paginating the results you will end up with a collection of Restaurant models (even if there is only one), so you will need to loop through them to get access to the offers for each model. I would also suggest eager loading the results e.g.

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() }}

这篇关于问题查询laravel雄辩的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆