【问题标题】:Laravel Collection trying to get property 'vote' of non-objectLaravel Collection 试图获得非对象的属性“投票”
【发布时间】:2020-05-22 02:06:54
【问题描述】:

这不是一个重复的问题,我已经尝试了迄今为止在 StackOverflow 中找到的大多数解决方案。

我有一个控制器将 Laravel 集合传递给这样的视图:

$votes = Vote::where('spid', '=', $id)->where('user_id', '=', Auth::user()->id)->get()->keyBy('comment_id');

它会产生类似的东西:

 App\Vote Object 
( [attributes:protected] => Array ( [id] => 2 [comment_id] => 13 [user_id] => 1 [vote] => 1 [spid] => 101190045 ) )

(还有incrementingkeyType等其他属性,但都被省略了)。

然而,当我在视图中使用这样的东西时,

{{$votes->get($comment->id)->vote}}

我明白了:

Trying to get property 'vote' of non-object

当我尝试时

{{$votes->get($comment->id)['vote']}}

我明白了:

Trying to access array offset on value of type null

我确定传递的$votes 是有效的,因为当我在视图中执行{{($votes->get($comment->id)->vote))}} 时,我得到{"id":2,"comment_id":13,"user_id":1,"vote":1,"spid":101190045}

当我也执行dd($votes->get($comment->id)->vote) 时,奇怪的是,它返回了正确的值。

【问题讨论】:

  • 我假设{{$votes->get($comment->id)->vote}}@foreach 循环内?也许您的某些$comment->id 不在您的$votes 对象内
  • 阅读keyBy的文档及其用法,会更清楚。你在collection中的key变成了category ID,你不需要使用get方法来获取它。使用普通的 []。
  • @ChristopheHubert 是的,它在 foreach 循环中。如果没有$votes->get($comment->id),如果该值为空,我将如何“捕捉”它?

标签: php mysql laravel eloquent


【解决方案1】:

感谢 Christophe Hubert,我意识到它在 foreach 循环中,并且一些结果返回了 null。我刚刚做了

{{$votes->get($comment->id)->vote ?? 0}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2019-01-09
    • 2015-09-22
    • 2017-03-20
    • 2014-03-25
    • 2015-01-25
    相关资源
    最近更新 更多