【问题标题】:Showing Empty after using eloquent un laravel在 laravel 中使用 eloquent 后显示为空
【发布时间】:2019-03-02 11:41:46
【问题描述】:

我的项目中有MyRoom.php 和TotalCity.php,其中每个房间都在一个城市内进行分类

所以我在 MyRoom.php 中这样做了

public function location()
{
    return $this->belongsTo(TotalCity::class, 'location_id')->withTrashed();
}

我在 TotalCity.php 中做了这个

public function location()
{
    return $this->hasMany(MyRoom::class , 'total_city_id')->withTrashed();
}

我已经用这样的路由和控制器传递了 id 主页.blade.php id)}}">{{ $row->name }}

web.php

Route::get('/city/{id}/rooms/','SiteController@room')->name('room');

站点控制器.php

public function room($id) {
    $room = TotalCity::find($id)->location;
    return view('frontend.pages.rooms', compact('room'));
}

rooms.blade.php

@foreach($room as $row)
        <div class="room">
            <a href="{{ route('description',$row->id) }}"><img src="{{ asset(env('UPLOAD_PATH').'/' . $row['photoi1']) }}"/></a>
        </div>
        @endforeach

但这并没有显示任何城市的任何房间,而我已经在我的数据库中存储了城市和特定城市下的房间。

【问题讨论】:

    标签: php laravel orm eloquent


    【解决方案1】:

    在关系方法中,你也应该提到外键和所有者键, 例如在 MyRoom.php 中:

    public function location()
    {
        return $this->belongsTo(TotalCity::class, 'location_id', 'total_city_primary_key')->withTrashed();
    }
    

    您可以阅读laravel documentioation了解更多详情。

    【讨论】:

    • 还是一样 我可以请你用teamviewer几分钟吗?
    • 其实外键和本地键都不需要。
    【解决方案2】:

    TotalCity 模型中的foreignKey 错误:

    public function location(){
        return $this->hasMany(MyRoom::class, 'location_id')->withTrashed();
    }
    

    【讨论】:

      【解决方案3】:

      我强烈建议您将模型的名称更改为 City 和 Room。如果您不想这样做,请确保在两个模型中都将它们连接到正确的表,您可以在两个模型中使用 $table 变量来实现这一点,如下所示:

      $table = 'your_table_name';
      

      这将确保表连接正确。

      此外,您应该进行一些更改:

      在您的 TotalCity 模型中执行以下操作:

      public function rooms()
      {
          return $this->hasMany(MyRoom::class , 'total_city_id')->withTrashed();
      }
      

      在您的 MyRoom 模型中执行以下操作:

      public function city()
      {
          return $this->belongsTo(TotalCity::class)->withTrashed();
      }
      

      在您的 SiteController 中执行以下操作:

      public function room($id) {
          $rooms = TotalCity::find($id)->rooms;
          return view('frontend.pages.rooms', compact('rooms'));
      }
      

      在您的视图中

      @foreach($rooms as $room)
              <h2>{{$room->name}}</h2>
              <div class="room">
                  <a href="{{ route('description',$room->id) }}"><img src="{{ asset(env('UPLOAD_PATH').'/' . $room['photoi1']) }}"/></a>
              </div>
      @endforeach
      

      【讨论】:

      • 我很高兴能帮上忙,朋友。请接受这个答案(检查按钮):)
      猜你喜欢
      • 2021-12-28
      • 2018-02-19
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      相关资源
      最近更新 更多