我有两个模型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
先感谢您!