【发布时间】: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 ) )
(还有incrementing或keyType等其他属性,但都被省略了)。
然而,当我在视图中使用这样的东西时,
{{$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