I have two models
named: League ans User
There's a pivot
table named: league_user
contains this structure:
id
user_id
league_id
joined_at
rank
payment_id
created_at
updated_at
This is my Models:
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');
}
}
And User Model:
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');
}
}
Now when I want to access to the rank
or joined_at
in my pivot table, it seems something is wrong or at least I'm doing that in a wrong manner.
I tried this:
foreach ( $leagues as $league )
{
$pivot[] = $league->pivot;
}
dd($pivot);
}
to check my pivot behavior, and I did check $league->pivot->rank
or $league->pivot->joined_at
either, but pivot
table seems to be null !
Can any one tell me what's wrong in my code?
I saw these links:
and...
if league_user
table with primary key ['league_id', 'user_id']
, you should be able to access the leagues like
$user = user::find(1);
$leagues = $user->leagues;
and can loop through
@foreach($leagues as $league)
{{ $league->rank }}
{{ $league->joined_at }}
@endofreach
For that in User model it should be
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function leagues()
{
return $this->belongsToMany('App\League');
}
}
and in League model
class League extends Model
{
/**
* The roles that belong to the user.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
}
refer docs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.