使用laravel 5.7,数据透视表返回null。*

问题描述 投票:0回答:1

我有两个qazxsw poi,名为:League和User

有一个models表名为: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

laraveldaily

laracast

和...

php laravel laravel-5 pivot-table
1个回答
0
投票

如果laravel documentation表与主键league_user,你应该能够访问联赛像

['league_id', 'user_id']

并且可以循环

$user = user::find(1);
$leagues  = $user->leagues;

对于用户模型中的那个应该是

@foreach($leagues as $league)
    {{ $league->rank }}
    {{ $league->joined_at }}
@endofreach

在联盟模式中

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function leagues()
    {
        return $this->belongsToMany('App\League');
    }
}

请参阅class League extends Model { /** * The roles that belong to the user. */ public function users() { return $this->belongsToMany('App\User'); } }

© www.soinside.com 2019 - 2024. All rights reserved.