drg17404 2019-07-30 12:05
浏览 54
已采纳

无法从表模型中获取名称并使用laravel在视图中显示它

I am trying to fetch the subject_name from the table subject using the subject_id I stored in the users table but whenever I try to do that I get this error. Any help ?

The relationship is ONE USER CAN ONLY HAVE ONE SUBJECT REGISTERED AND ONE SUBJECT CAN BE SELECTED BY MANY USERS SO ITS ONE TO MANY RELATIONSHIP

`Illuminate \ Database \ QueryException (42S02)
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myunimentor_database.subject_user' doesn't exist (SQL: select `subjects`.*, `subject_user`.`user_id` as `pivot_user_id`, `subject_user`.`subject_id` as `pivot_subject_id` from `subjects` inner join `subject_user` on `subjects`.`id` = `subject_user`.`subject_id` where `subject_user`.`user_id` = 1)
Previous exceptions
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myunimentor_database.subject_user' doesn't exist (42S02)`

User Model

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

use App\UserType;
use App\Subject;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'type', 'username', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getAllUsers() {
        return User::all();
     }

     public function userTypes()
     {
         return $this->belongsTo('App\Users');
     }

     public function subjects()
    {
        return $this->belongsToMany('App\Subject');
    }
}

Subject Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;
use App\SubjectKeyword;

class Subject extends Model
{
    protected $fillable = [
        'subject_name', 
    ];

    public function users()
    {
        return $this->hasMany('App\User');
    }

    public function subjectKeywords()
    {
        return $this->hasMany('App\SUbjectKeyword');
    }
}



@extends('layout.dashboard')
@section('title', 'Add Subjects')

@section('content')

<p> You can only add <font color='#5FCF80'>1 Subject</font> <br/>
        follow by 5 keywords for Non Mentors to search you. </br/>
        <font color='#5FCF80'> <b>HAPPY MENTORING!</b></font></p>

<br/>

Controller

$users = User::where('id', Auth::user()->id)->first();

            echo $users;
            $users->subject_id = $s1;

            echo Auth::user()->subjects->subject_name;
            die();

View

@section('content1')
<p>Mentor Subject:
    {{ Auth::user()->subject->subject_name }}
</p>

    <p> Specified Keywords: 
        @foreach($subjectKeywords as $sk)
            <li> {{ $sk ['keyword_title1'] }} </li>
            <li> {{ $sk ['keyword_title2'] }} </li>
            <li> {{ $sk ['keyword_title3'] }} </li>
            <li> {{ $sk ['keyword_title4'] }} </li>
            <li> {{ $sk ['keyword_title5x'] }} </li>
        @endforeach
    </p>

    <form class="form-horizontal" method="POST" role="form"  action="/add-new-subject" >

        {{ csrf_field() }}


        <div class="form-group" data-rule="required">
            <label>Subject Titles</label> <br/>

            <select id="ddselect" name='subject_name' class="signup" required >
                <option value=""> Select Subject to Monitor </option>
                @foreach($subjectDetails as $s)
                    <option id={{ $s['id'] }} name={{ $s['id'] }} value={{ $s['id'] }}>{{ $s['subject_name'] }}</option>
                @endforeach
            </select>

            <div class="validation"></div>
        </div>

        <div class="form-group">
            <input type="text" name="k1" class="signup-control form" id="k1" placeholder="Keyword 1"/>
            <div class="validation"></div>

            <input type="text" name="k2" class="signup-control form" id="k2" placeholder="Keyword 2"/>
            <div class="validation"></div>

            <input type="text" name="k3" class="signup-control form" id="k3" placeholder="Keyword 3"/>
            <div class="validation"></div>
        </div>

        <div class="form-group">
            <input type="text" name="k4" class="signup-control form" id="k4" placeholder="Keyword 4"/>
            <div class="validation"></div>

            <input type="text" name="k5" class="signup-control form" id="k5" placeholder="Keyword 5"/>
            <div class="validation"></div>
        </div>
    </div>

    <br/>

<div class="col-xs-12">
    <!-- Button -->
    <button type="submit" id="submit" name="submit" class="form contact-form-button light-form-button oswald light">Select Subject</button>
</div>
</form>

@endsection        
@endsection
  • 写回答

2条回答 默认 最新

  • douxi3233 2019-07-30 12:10
    关注

    In your User model Relation should be belongsTo()

     public function subject(){
        return $this->belongsTo('App\Subject','subject_id','id');
    }
    

    Now you can access your subject name as Auth::user()->subject->subject_name

    As you said one user have only one subject so User belongsTo only one subject.

    Subject can have multiple users it means HasMany. User model -> belongsTo with subject Subject Model -> HasMany with users

    Please check here for more info. https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里