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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?