【发布时间】:2019-04-30 10:57:14
【问题描述】:
我有两个models,名称分别为:League和User
有一个pivot 表名为:league_user 包含这个结构:
id
user_id
league_id
joined_at
rank
payment_id
created_at
updated_at
这是我的模特:
class League extends Model
{
protected $fillable = [
'name', 'capacity', 'is_open', 'started_at', 'finished_at', 'is_free', 'price', 'level', 'user_id', 'closed_by', 'edited_by'
];
protected $hidden = [];
/*
* User Relationship
*/
function user()
{
return $this->belongsTo(User::class);
}
/*
* Editor Relationship
*/
public function editor()
{
return $this->belongsTo(User::class, 'edited_by');
}
/*
* All users Relationship
*/
public function all_users()
{
return $this->belongsToMany(User::class)->withTimestamps()->withPivot('rank', 'joined_at');
}
}
和用户模型:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'family', 'email', 'mobile', 'password', 'username', 'team', 'email_verified_at', 'mobile_verified_at', 'role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/*
* Roles ralationship
*/
public function role()
{
return $this->belongsTo(Role::class);
}
/*
* Question Relationship
*/
public function questions()
{
return $this->hasMany(Question::class);
}
/*
* League Relationship
*/
public function leagues()
{
return $this->hasMany(League::class);
}
/*
* Setting Relationship
*/
public function setting()
{
return $this->hasOne(UserSetting::class);
}
/*
* All Leagues that User Joined
*/
public function all_leagues()
{
return $this->belongsToMany(League::class)->withTimestamps()->withPivot('rank', 'joined_at');
}
}
现在,当我想访问我的数据透视表中的 rank 或 joined_at 时,似乎有问题,或者至少我以错误的方式进行操作。
我试过了:
foreach ( $leagues as $league )
{
$pivot[] = $league->pivot;
}
dd($pivot);
}
检查我的枢轴行为,我确实检查了$league->pivot->rank 或$league->pivot->joined_at,但pivot 表似乎是null!
谁能告诉我我的代码有什么问题?
我看到了这些链接:
还有……
【问题讨论】:
-
数据透视表不应该有属于某个实体的额外列。
-
请您说明您是如何为 foreach 获取
$leagues变量的? -
@RossWilson 我确实尝试了两种方式,首先;使用
League::orderBy('price', 'asc')->orderBy('id', 'asc')->paginate(10);和第二个作为这个问题的答案:#user = User::find(Auth;;User()->id)和$user->leagues -
好的。为了能够访问数据透视表,你总是需要加载关系,否则 Laravel 不会知道你想要哪个数据透视表。另外,仅供参考,
User::find(Auth::user()->id)没有意义,因为Auth::user()将返回该用户(您实际上是在加载 User 模型两次)。
标签: php laravel laravel-5 pivot-table