【问题标题】:Issue querying laravel eloquent relationship查询 laravel eloquent 关系的问题
【发布时间】:2019-02-03 05:11:49
【问题描述】:

这是参考这个问题:

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()之后

【问题讨论】:

  • 为什么建议的方式有效?错误是什么?请更具体。
  • 你想做什么?您是否要参考与餐厅相关的优惠?
  • 是的,我想列出特定餐厅的所有优惠。
  • 另外,请尝试$this-&gt;hasMany('App\Offer');
  • 如果你 dd(\App\Restaurant::with('offer'));在控制器中?

标签: php laravel orm


【解决方案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】:

    你能换吗 $restaurants = \App\Restaurant::paginate(3); 并修改刀片代码说

    <?php
      foreach($restraunts_data as $resturant) {
         if(count($restaurant->offer) {
            print_r($restaurant->offer);
         }
      }
    ?>
    

    【讨论】:

      【解决方案3】:

      您使用的模型不正确。您不运行任何查询,并尝试在 Restaurant 类上运行静态方法,而不选择任何餐馆。据我所知,这不是 Eloquent 支持的。如果您查看错误消息,它会抱怨没有属性$offer

      尝试运行一些查询,然后选择相关的Offer。这应该可以按预期工作。

      例如:

      $offers = \App\Restaurant::find(1)->offer;
      

      这将返回 ID 为 1 的 Restaurant 的许多 Offer 关系。

      【讨论】:

      • 查询由分页方法处理,就像你在没有任何条件的情况下运行Restaurant::get()..
      猜你喜欢
      • 2013-10-03
      • 2017-07-19
      • 2015-06-27
      • 1970-01-01
      • 2021-09-25
      • 2015-01-21
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多