我正在尝试展示Races +参加比赛的人,我正在使用桌面关系,但我不确定我是否正确使用它。
视图:
@foreach($leagues->races as $race)
<!-- ATTENDANCE track -->
<div class="col s12 m6">
<div class="card">
<div class="card-image">
<img src="{{ asset("img/tracks/.png") }}">
<span class="card-title red attendance-track-box"><b>{{$race->event}}</b></span>
</div>
<div class="card-content attendance-content">
<ul>
@foreach($race->attendances as $attendance)
@if($attendance->status == 1)
<li class="border-left-green">{{$attendance->user->username}}</li>
@elseif($attendance->status == 2)
<li class="border-left-red"></li>
@elseif($attendance->status == 3)
<li class="border-left-cyan"></li>
@endif
@endforeach
</ul>
</div>
<div class="card-action">
<a class="waves-effect waves-light btn green">Yes</a> <a class="waves-effect waves-light btn red">No</a> <a class="waves-effect waves-light btn">Maybe</a>
</div>
</div>
</div>
@endforeach
模特联赛:
class Leagues extends Model
{
//
public function teams(){
return $this->hasMany('App\teams');
}
public function races(){
return $this->hasMany('App\races');
}
}
模特种族:
class Races extends Model
{
//
public function attendances()
{
return $this->hasMany('App\attendances');
}
}
模型驱动程序:(使用此驱动程序列表)
class Drivers extends Model
{
//
public function user(){
return $this->belongsTo('App\Users', 'users_id', 'id');
}
}
模特出席:
class attendances extends Model
{
//
public function user(){
return $this->belongsTo('App\Users', 'users_id', 'id');
}
}
模型用户
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
//
}
我发布了Drivers模型,因为我也调用了belongsTo。 基本上,我复制了代码,它适用于驱动程序,但它不适合出席
我得到错误:
尝试获取非对象
的属性'用户名'
user.php的
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'psn', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
答案 0 :(得分:1)
您的模型关系仅执行逆belongsTo
。如果你想使用belongsTo
,你的模型关系需要双向进行,但你的关系只是相反。首先使用hasMany
,hasOne
等定义关系,然后在另一个模型中定义逆。
示例驱动程序:
class Drivers extends Model
{
public function user(){
return $this->belongsTo('App\Users', 'users_id', 'id');
}
}
出席人数示例:
class attendances extends Model
{
public function user(){
return $this->belongsTo('App\Users', 'users_id', 'id');
}
}
示例用户:
class Users extends Model
{
public function attendances()
{
return $this->hasMany('App\attendances');
}
public function drivers()
{
return $this->hasMany('App\Drivers');
}
}
每个班级都需要互相参考。一个用hasMany
,hasOne
等来定义关系,另一个用belongsTo
来定义关系的倒数。