Laravel 模型关系和路由获取模型id
我有以下路线:Laravel 模型关系和路由获取模型id,laravel,eloquent,Laravel,Eloquent,我有以下路线: Route::get('notes/main', function(){ $destinations = Destination::where('show', '=','1')->get(); $notes = Destination::find($destination->id)->notes()->get(); return View::make('notes.main') ->w
Route::get('notes/main', function(){
$destinations = Destination::where('show', '=','1')->get();
$notes = Destination::find($destination->id)->notes()->get();
return View::make('notes.main')
->with('destinations', $destinations);
});
//关系模型:
<?php
class Destination extends Eloquent {
public function notes()
{
return $this->has_many('Note');
}
}
<?php
class Note extends Eloquent
{
public function destination()
{
return $this->belongs_to('Destination');
}
}
在您的路由中,您没有向视图发送$notes变量
我会怎么做:
$destinations = Destination::where('show', '=','1')->get();
$destinations->notes = Destination::find($destination->id)->notes()->get();
然后,鉴于:
@foreach( $destinations as $destination)
{{ $destination->name}}<br>
{{ $destination->notes->text }}
@endforeach
@foreach($destinations作为$destination)
{{$destination->name}}
{{$destination->notes->text}
@endforeach
您在路线中使用$destination->id,但它似乎尚未定义。问题是,您想用代码实现什么?
与:
您只获取一个特定目的地的注释(到目前为止,$destination尚未定义。您可以使用destination::all()->first()获取第一个,或者使用destination::find(id),id替换为所需目的地的主键值)
但我想你不想那样。从您的输出来看,似乎您希望每个目的地都有一个输出,每个目的地下面都有相应的注释
控制器:
//gets all the destinations
$destinations = Destination::where('show', '=','1')->get();
return View::make('notes.main')
->with('destinations', $destinations);
视图:
@foreach($destinations作为$destination)
{{$destination->name}}
@foreach($destination->notes as$note)
{{$note->text}}
@endforeach
@endforeach
没有对此进行测试,但这样您的视图将显示所有目的地以及每个目的地的所有注释。确定
在最后一部分,这在最后得到了解决
函数isset和empty不起作用,奇怪:
@if ($note->title == 'shorttext')
首先你问了一个问题,我给了你一个正确的答案。
您将我的答案标记为已接受,但稍后您将编辑初始问题以添加另一个问题(您应该为此创建一个新线程)。
然后你创建自己的答案,只回答你最初问题的一部分,并将其标记为好的解决方案
我可以告诉你为什么你的isset和empty不起作用,但如果你根本不重视我的帮助,我为什么要这样做?我得到:Undefined variable:Destination你的评论似乎被删掉了,但我看到我在输出中犯了一个错误。它不应该是$destination->notes->text,而是$note->text。我会相应地编辑它
$destinations = Destination::where('show', '=','1')->get();
$notes = Destination::find($destination->id)->notes()->get();
//gets all the destinations
$destinations = Destination::where('show', '=','1')->get();
return View::make('notes.main')
->with('destinations', $destinations);
@foreach( $destinations as $destination)
{{ $destination->name}}<br>
@foreach($destination->notes as $note)
{{ $note->text }} <br>
@endforeach
<hr>
@endforeach
@if ($note->title == 'shorttext')