简体   繁体   English

Laravel在对象中检索数据对象

[英]Laravel retrieved data object in object

In my ArticleController I have: 在我的ArticleController中,我有:

public function index()
    {
        $article= Article::with('ratingAvg')->get();        
        return view('article.index',['article' => $article]);
    }

And in my Article model: 在我的文章模型中:

public function ratingAvg()
    {
      return $this->hasOne('App\Rating', 'article_id')
        ->selectRaw('article_id AVG(rating) as rating')
        ->groupBy('article_id');
    }

In article.index : article.index中

@foreach ($article as $a)
  <p>{{$a}}</p>
@endforeach

As a result I receive the following data from the database: 结果,我从数据库收到以下数据:

{"id":10,"name":"Article1","rating_avg":{"article_id":10,"rating":"4.0"}}

When running dd($article); 当运行dd($article); in the ArticleController I receive: ArticleController中,我收到:

Collection {#194 ▼
  #items: array:2 [▼
    0 => Article{#188 ▼
      #table: "articles"
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:12 [▶]
      #original: array:12 [▶]
      #relations: array:1 [▼
        "ratingAvg" => Rating {#195 ▼
          #table: "ratings"
          #connection: null
          #primaryKey: "id"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:2 [▼
            "article_id" => 10
            "rating" => "4.0"
          ]
        }
      ]
    }
  ]
}

My question is, how can I display the rating value from the rating_avg object? 我的问题是,如何显示rating_avg对象中的评级值?

Here: 这里:

$article = Article::with('ratingAvg')->get(); 

you are eager-loading this relation: 您渴望加载此关系:

public function ratingAvg()

So you should access the relation in the view this way: 因此,您应该以这种方式在视图中访问该关系:

@foreach ($article as $a)
    <p>{{ $a->ratingAvg->rating }}</p>
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM