我试图通过ISBN(书桌的PK)显示一本书的评论,但出现以下错误:
Invalid argument supplied for foreach
我在Helper类中使用Laravel关系和foreach来从以下查询中获取记录:
public function comments()
{
return $this->hasMany(Comment::class, "ISBN", "ISBN");
}
这是我的Book模型的评论关系:
@foreach(getCommentsByISBN(session("isbn")) as $comment)
<div class="form-group">
<h3>
{{ getUserWhoPostedComment($comment->email) }}
</h3>
<p>
{{ $comment->commentary }}
</p>
@if(Session::has("username") && isAdmin(session("username")))
<button type="button" onclick="openModal('{{$comment->commentary}}')"
name="warningButton" class="btn btn-warning" data-toggle="modal"
data-target="#modalWarning">
<i class="fas fa-exclamation-circle"></i>
</button>
@endif
<hr>
<span>
Hace: {{ getTimeWherePostedComment($comment->publicated_at) }}
</span>
</div>
@endforeach
这是我显示评论的视图:
<?php
$number = array (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
echo "<style>table{border-collapse:collapse;}</style>";
echo "<table border ='1px'; >";
echo "<tr>
<th>EVEN NUMBERS</th>
<th>ODD NUMBERS</th>
</tr>";
for ($i=0; $i < count($number); $i++) {
echo "<tr>";
if ($number[$i] % 2 == 0) {
echo " <td>$number[$i] </td>";
}
else {
echo "<td><b>$number[$i]</b></td>";
}
echo "</tr>";
}
echo "</table>";
?>
谢谢!
答案 0 :(得分:2)
我认为您的助手返回空缺,因为找不到与该ISBN有关的书。
我认为它应该看起来像这样
function getCommentsByISBN($isbn)
{
if ($book = Book::where("ISBN", $isbn)->first()) {
return $book->comments;
}
}
在刀片中,您的顶部看起来应该像
@php
$comments = getCommentsByISBN(session("isbn")) ?: [];
@endphp
@foreach($comments as $comment)
<div class="form-group">
/// Rest of the code