【发布时间】:2019-09-13 09:25:01
【问题描述】:
我有两个模型 User 和 AccountType
class 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 时,它工作正常。
ErrorException
Undefined offset: 1
详情在这里 - https://flareapp.io/share/jKPgOZPa
提前谢谢你!
【问题讨论】:
-
你遇到了什么错误?
-
@DilipHirapara 我已将这些添加到我的问题中。对不起:)
-
用户表中是否所有用户都有账户类型ID?
-
是的,他们默认得到它。
-
我不是说那是一个错误,但你能不能改变并检查一下,如果 1)
accountType()名称应该是小的'account_type()'2) 在 AccountType 模型中return $this->hasMany('App\User','account_type_id', 'id');