【问题标题】:Laravel - Get relationship without Route Model Binding (w/o parameter)Laravel - 获取没有路由模型绑定的关系(无参数)
【发布时间】:2018-10-07 22:10:37
【问题描述】:

我有一个学生可能有许多科目的关系表。在主页(/),我想显示来自关系的数据没有任何路由参数。

学生模型

class Student extends Model
{
  protected $fillable = ['name', 'class', 'subjects'];
  public function all_marks()
  {
    return $this->hasMany(Marks::class, 'student_id');
  }
}

标记模型

class Marks extends Model
{

  protected $fillable = ['name', 'student_id', 'subjects', 'marks'];
  public function marks()
  {
    return $this->belongsTo(Student::class, 'student_id');
  }
}

路线

Route::get('/', 'Controller@home')->name('home_page');

控制器

 public function home()
  {
    $students = Student::orderBy('created_at', 'asc')->get();
    $minimum_marks = Student::with(['marks'])->where(['student_id'=>$students->id])->min('marks');
    return view ('home', compact('students', 'minimum_marks'));  
}

查看

@foreach($studens as $student)
 Name: {{ $student->name}}
 Min. marks: {{ $minimum_marks }}
@endforeach

我来了

此集合实例上不存在属性 [id]。

我知道我需要有路线

Route::get('/{$id}', 'Controller@home')->name('home_page');并将函数更改为public function home($id)

但我想在domain.com 主页而不是domain.com/1 上显示这些

听说过显式路由,但了解不多。

【问题讨论】:

    标签: laravel routes url-routing


    【解决方案1】:

    您正在尝试从此处的集合中获取属性 id

    ->where(['student_id'=>$students->id])
    

    该属性存在于模型的单个实例上,而您试图在模型集合上调用它,所以它不存在。

    【讨论】:

      猜你喜欢
      • 2015-12-08
      • 2017-01-10
      • 2018-07-28
      • 2018-02-12
      • 2018-01-18
      • 1970-01-01
      • 2017-07-06
      • 2021-05-24
      • 2016-06-04
      相关资源
      最近更新 更多