我如何在两个模型之间创建关系并将模型信息通过控制器传递给视图?

How can i create a relation beetwen two models and pass the model info on to the view through the controller?

我的学生模型

 /**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function fathers()
{
    return $this->belongsTo('App\Models\Father');
}

我的学生控制器

/**
 * Display the specified resource.
 *
 * @param ManageStudentRequest $request
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function show(ManageStudentRequest $request, $id)
{
    $student = Student::with('fathers')->find($id);

    return view('students.show')->withStudent($student);
}

还有我的 Blade View

<tr>
    <th>NOMBRE</th>
    <td>{{ $student->father->first_name }} {{ $student->father->last_name }}</td>
</tr>

问题是我犯了这个错误:

Trying to get property of non-object (View: C:\laragon\www\App\resources\views\students\partials\show\show-overview.blade.php) (View: C:\laragon\www\App\resources\views\students\partials\show\show-overview.blade.php)

我非常需要帮助,任何有用的东西,tyvm。

如果这是你想要的逻辑,你应该设置你的结构以在学生和父亲之间建立多对多关系,所以:

public function fathers()
{
    return $this->belongsToMany('App\Models\Father');

    //Also define the inverse relationship on the Father model.
}

现在假设你已经做到了:

在这个查询中 $student = Student::with('fathers')->find($id); 只需附加 first(),它看起来像这样:

$student = Student::with('fathers')->find($id)->first();

然后在您看来,您可以像这样访问它们:

<td>{{ $student->father->first_name }} {{ $student->father->last_name }}</td>