php - Laravel 5.6 - 一对多关系
问题描述
我正在学习laravel和php。我有一个成员对象,它只能有 1 种语言选项,但有多种语言选项可供选择。成员对象是我的主要对象。我想测试我是否正确设置了我的关系,但在测试时没有看到所需的结果(我应该只看到在语言字段中选择的语言,而不是每个成员的所有列属性,如下所示)。所以这是我的 show.blade.php 文件的输出:
这是我的 show.blade.php 文件:
@extends('layouts.master')
@section('title', $member->name)
@section('content')
<h1>Member Details: </h1>
<p>Name: {{$member->name}}</p>
<p>Surname: {{$member->surname}}</p>
<p>ID Nr: {{$member->id_number}}</p>
<p>Mobile Nr: {{$member->mobile_number}}</p>
<p>Email: {{$member->email}}</p>
<p>D.O.B: {{$member->date_of_birth}}</p>
<p>Language:{{$member->language}}</p>
<p>Created At: {{$member->created_at}}</p>
<div class="page-header">
<a href="{{action('MemberController@edit', $member->id)}}" class="btn btn-info">Edit</a>
</div>
@endsection
这是我的语言表迁移文件:
public function up()
{
Schema::create('languages', function (Blueprint $table) {
$table->increments('id');
$table->integer('member_id')->unsigned();
$table->string('name');
$table->timestamps();
});
Schema::table('languages', function(Blueprint $table) {
$table->foreign('member_id')->references('id')->on('members');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('languages', function(Blueprint $table) {
$table->dropForeign('languages_member_id_foreign');
});
Schema::dropIfExists('languages');
}
这是我的成员表迁移文件:
public function up()
{
Schema::table('members', function (Blueprint $table) {
$table->string('name');
$table->string('surname');
$table->string('id_number')->unique();
$table->string('mobile_number');
$table->string('email');
$table->date('date_of_birth');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('members', function (Blueprint $table) {
$table->dropColumn('name');
$table->dropColumn('surname');
$table->dropColumn('id_number')->unique();
$table->dropColumn('mobile_number');
$table->dropColumn('email');
$table->dropColumn('date_of_birth');
});
}
最后是我的成员模型:
class Member extends Model
{
public function language() {
return $this->hasMany('App\Language');//('Language') = name of the Language Model
}
}
我哪里错了?
解决方案
您看到对象的 JSON 表示的原因是,当您将{{$member->language}}
. 这代表整个App\Language
对象。
尝试使用{{$member->language->first()->name}}
来指定您只要求name
对象的变量。
为了显示所有语言,您需要$member->language
使用以下命令遍历集合:
@foreach ($member->language as $language)
{{ $language->name }}
@endforeach
推荐阅读
- database - 用于存储大小为 100 MB 到 1 GB 的二进制数据的选项
- javascript - 使用 HTML5 Canvas 呈现时如何消除文本的边缘?
- node.js - 从查询的顶级模型检查关联模型
- android - kotlin 中的回收站查看项目点击监听器
- python - for 循环在 for 循环中给出关键错误我正在给出列表
- c# - MaskedTextBox 在 C# 中进行验证
- c++ - c++ Qt中的计算属性
- php - 查询数据和排列数据 Laravel
- javascript - Response.Redirect(" ") 或 window.location=""
- php - Laravel 雄辩的构建查询