【发布时间】:2016-09-11 12:32:39
【问题描述】:
我有这些关系类似于文档和关系设置。帖子有很多 cmets 和 rate。 cmets 有很多费率。它是一种多态关系。
posts
id - integer
user_id -integer
body - text
comments
id - integer
post_id - integer
user_id - integer
body - string
rates
id - integer
user_id - integer
rate - integer
likable_id - integer
likable_type - string
如何订购价格最高的帖子和 cmets?我通过这种方式获取帖子和相应的费率。但默认情况下,帖子是按 id 排序的。评论也是一样。
$posts=Post::with('comments','comments.rates','rates')->get();
foreach($posts as $post)
{
$post=$post->body; //post
foreach($post->comments as $comment)
{
$comment=$comment->body; //comment
$rateofcomment=$comment->rates->sum('rate'); //rate of comment
}
$rateofpost=$post->rates->sum('rate'); //rate of post
}
更新 在 post.php 和 comment.php 中更改
public function rates()
{
return $this->morphOne('App\Rate', 'likable')
->selectRaw('SUM(rate) as rateSum, likable_id')
->groupBy('likable_id');
}
在 rate.php 中
public function likable()
{
return $this->morphTo();
}
实际上,下面的这段代码适用于第一篇文章。意味着如果我死了; foreach 执行的其余部分显示费率。
$posts=Post::with('comments','comments.rates','rates')->get();
foreach($posts as $post)
{
$post=$post->body; //post
$rateofpost = $post->rates->rateSum;
print_r($rateofpost); die;
但是。如果我尝试完成 foreach 循环,它会显示熟悉的错误 Trying to get property of non object?这是因为所有帖子和 cmets 可能没有 rateSum。我怎样才能避免这种情况?
【问题讨论】:
-
如果你所有的帖子和 cmets 都有
rateSum,那么它工作正常吗?请检查这个。然后我们可以为剩下的问题找出解决方案。 :) -
@sha-1 是的。我刚刚检查过了。
-
@sha-1 用 isset() 解决了这个问题。感谢您的所有努力,
-
您也可以使用Laravel Accessor and mutators 来检查
rates是否为空,然后使用默认值。但是你的也可以。感谢您将我的答案标记为已接受。 :)