发布于:
2022-06-06 14:04:35
通过
pivot
属性来访问关联表的字段$user = App\User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
+---------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | user_id | int(10) unsigned | NO | | NULL | | | role_id | int(10) unsigned | NO | | NULL | | | department_id | int(10) unsigned | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +---------------+------------------+------+-----+---------+----------------+
foreach($user->departments as $department) { $role = Role::find($department->privot->role_id); }
namespace App\PivotModels; use Illuminate\Database\Eloquent\Relations\Pivot; use App\Models\Role;use App\Models\Department; class UserRole extends Pivot{ public function role(){ return $this->belongsTo(Role::class); } public function department(){ return $this->belongsTo(Department::class); } }
public function newPivot(Model $parent, array $attributes, $table, $exists) { if ($parent instanceof User) { return new UserRole($parent, $attributes, $table, $exists); } return parent::newPivot($parent, $attributes, $table, $exists); }
public function departments()
{
return $this->belongsToMany(Department::class, 'user_role', 'department_id', 'user_id')
->withPivot(['department_id', 'user_id', 'role_id']) // 这行要把中间表的字段都加上
->withTimestamps();
}