【问题标题】:model relationship and routes get model id模型关系和路由获取模型id
【发布时间】:2013-05-29 12:06:26
【问题描述】:

我有以下路线:

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');
        }

}

//查看:

@foreach( $destinations as $destination)

{{ $destination->name}}<br>
{ $notes->destination->text }} // this isn't echoed
@endforeach

过滤并定义 $destination->id 的正确方法是什么

谢谢

如何过滤循环内 if 语句中的注释? @if (isset($note->title) != 'shorttext')

          @else
           <p> {{ $note->text }} </p>
          @endif  
          @endforeach

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您在 Route 中使用了 $destination->id,但它似乎尚未定义。问题是,你想用你的代码实现什么? 与:

    $destinations = Destination::where('show', '=','1')->get();
    $notes = Destination::find($destination->id)->notes()->get();
    

    你只得到一个特定目的地的注释(到目前为止,$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 as $destination)
      {{ $destination->name}}<br>
      @foreach($destination->notes as $note)
         {{ $note->text }} <br>
      @endforeach
      <hr>
    @endforeach
    

    没有对此进行测试,但这样您的视图会显示您的所有目的地以及每个目的地的所有注释。

    【讨论】:

    • 您的评论似乎被删减了,但我看到我在输出中犯了一个错误。它不应该是 $destination->notes->text 而是 $note->text。我会相应地编辑它
    【解决方案2】:

    在您的路线中,您没有将 $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
    

    【讨论】:

    • 我得到:未定义的变量:目的地
    【解决方案3】:

    所以首先你问了一个问题,我给了你一个正确的答案。 您将我的答案标记为已接受,但稍后您编辑初始问题以添加另一个问题(您应该为此创建一个新线程)。 然后您创建自己的答案,该答案仅回答您最初问题的一部分并将其标记为好的解决方案?

    我可以告诉你为什么你的 isset 和 empty 不起作用,但如果你根本不重视我的帮助,我为什么要告诉你?

    【讨论】:

      【解决方案4】:

      好的 对于最后一部分,这最终解决了 函数 isset 和 empty 不起作用,奇怪:

      @if ($note->title == 'shorttext')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 2018-02-12
        • 2018-10-07
        • 2013-03-25
        • 2019-09-24
        • 2015-10-09
        • 2014-12-13
        相关资源
        最近更新 更多