我有两个模型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
提前谢谢!
答案 0 :(得分:1)
您需要使用蛇案而不是骆驼案:
<td> {{ $user->account_type->account_type_name }} </td>
答案 1 :(得分:0)
好像您定义了错误的关系。您的用户模型应类似于:
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');
}
}
答案 2 :(得分:0)
我已将<td> {{ App\User::find($user->id)->accountType->account_type_name }} </td>
替换为{{1}},现在一切正常。
答案 3 :(得分:0)
您可以尝试一下。...我的工作正常。
$user->accountType->first() ->account_type_name