亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 BelongsTo() 在 Laravel 6 中不起作用?

為什么 BelongsTo() 在 Laravel 6 中不起作用?

PHP
拉莫斯之舞 2022-01-08 20:08:44
我有兩個模型User和AccountTypeclass User extends Authenticatable{    (...)    public function accountType()    {        return $this->belongsTo('App\AccountType', 'account_type_id', 'id');    }}class AccountType extends Model{  protected $table = 'account_types';  // protected $primaryKey = 'id';  public function users()  {      return $this->hasMany('App\User');  }}我的數據庫:        Schema::create('users', function (Blueprint $table) {            $table->bigIncrements('id');            $table->bigInteger('account_type_id')->unsigned();            $table->foreign('account_type_id')->references('id')->on('account_types');            $table->string('full_name');            $table->string('email')->unique();            $table->timestamp('email_verified_at')->nullable();            $table->string('password');            $table->rememberToken();            $table->timestamps();        });        Schema::create('account_types', function (Blueprint $table) {            $table->bigIncrements('id');            $table->string('account_type_name');        });當我使用 hasMany 時 - 一切都像魅力一樣,但是當我嘗試使用$user->accountType->account_type_name它時卻不起作用。我用來打印用戶的循環:                @foreach ($users as $user)                  <tr>                    <td>{{ $user->full_name }}</td>                    <td>                      <a href="#" class="badge badge-pill badge-warning">No team</a>                    </td>                    <td>                      xyz                    </td>                    <td> {{ $user->accountType->account_type_name }} </td>                    <td><a href="mailto:{{ $user->email }}">{{ $user->email }}</a></td>                    <td>{{ $user->created_at }}</td>                  </tr>                @endforeach和錯誤。當我注釋掉$user->accountType->account_type_name它時, 它工作正常。ErrorExceptionUndefined offset: 1詳情在這里 - https://flareapp.io/share/jKPgOZPa
查看完整描述

3 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

您需要使用蛇盒而不是駱駝盒:

<td> {{ $user->account_type->account_type_name }} </td>


查看完整回答
反對 回復 2022-01-08
?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

看起來你定義了錯誤的關系。你的用戶模型應該是這樣的:


class User extends Authenticatable

{

    (...)


    public function accountType()

    {

        return $this->hasOne('App\AccountType', 'account_type_id', 'id');

    }

}

和帳戶類型模型應該是這樣的:


class AccountType extends Model

{

     protected $table = 'account_types';

    // protected $primaryKey = 'id';


    public function user()

    {

       return $this->belongsTo('App\User');

    }

}


查看完整回答
反對 回復 2022-01-08
?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

你可以試試這個..我的工作正常..

$user->accountType->first() ->account_type_name


查看完整回答
反對 回復 2022-01-08
  • 3 回答
  • 0 關注
  • 179 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號