为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 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 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号