2017-12-27 807 views
5

所以,这里是我的控制器:为什么在Laravel中使用WHERE循环获取数据?

$topics = Topic::where('board_id', $id)->with('user')->get(); 
$topic = Topic::find($id); 
$board = Boards::where('id', $id)->get(); 
return view('boards.show')->with('topics', $topics)->with('topic', $topic)->with('board', $board); 

这里是生成的URL代码:

@foreach($board as $boards) 
<a href="/topics/create/{{$boards->id}}">Create New Post</a> 
<p>No Posts Found</p> 
@endforeach 

但是如果我删除foreach循环,它给错误:

Property [id] does not exist on this collection instance. 

但是,为什么我必须循环,如果它只从电路板表中获得一行?任何解决方案,不为每个循环运行?

回答

4

既然你只想得到一个物体,你不需要to use get() to get a collection。使用find()通过它来得到一个对象的主键:

$board = Boards::find($id); 

在视图中,您不需要使用@foreach循环:

<a href="/topics/create/{{ $board->id }}">Create New Post</a> 
+2

是的,这工作。再次感谢。 –

+1

另外你可以先使用()或采取(1) –

2

您可以使用Boards::find($id);Boards::findOrFail($id); insted的的Boards::where('id', $id)->get();为得到一个单row.Also使用

return view('boards.show')->with('topics', $topics)->with('topic', $topic)->with('board', $board); 

return view('boards.show',[ 
    'topics'=> $topics, 
    'topic'=> $topic, 
    'board'=> $board 
]); 

becouse传递正常值使用会话,查看是不是一个好的做法

+0

并且改变路由在laravel练习 –

相关问题