如何在Laravel中获取三级关联模型数据
解决方案
要在现有接口中获取第三级表EducationalAward的award字段,只需利用Eloquent的嵌套关联预加载功能,修改控制器方法即可:
public function getEducationalBackground($id) { $educationalBackground = EducationalBackground::with(['user', 'educationalAwards']) ->where('user_id', $id) ->get(); return response()->json($educationalBackground, 200); }
可选:仅返回指定字段
如果只需要EducationalAward中的award字段(而非所有字段),可以在预加载时指定字段列表(注意必须包含关联外键educational_background_id,否则无法正确关联数据):
public function getEducationalBackground($id) { $educationalBackground = EducationalBackground::with([ 'user', 'educationalAwards:id,educational_background_id,award' ]) ->where('user_id', $id) ->get(); return response()->json($educationalBackground, 200); }
原始代码参考
User模型
class User extends Authenticatable { use HasFactory, Notifiable, HasApiTokens, HasRoles; const MALE = 'male'; const FEMALE = 'female'; protected $guard_name = 'sanctum'; public function educationalBackgrounds() { return $this->hasMany("App\Models\Users\EducationalBackground", "user_id"); } public function seminars() { return $this->hasMany("App\Models\Users\Seminar", "user_id"); } }
EducationalBackground模型
class EducationalBackground extends Model { use HasFactory; protected $table = 'users.educational_backgrounds'; protected $fillable = [ 'user_id', 'studies_type', 'year', 'course', ]; public function user() { return $this->belongsTo('App\Models\User', 'user_id'); } public function educationalAwards() { return $this->hasMany("App\Models\Users\EducationalAward", "educational_background_id"); } }
EducationalAward模型
class EducationalAward extends Model { use HasFactory; protected $table = 'users.educational_awards'; protected $fillable = [ 'educational_background_id', 'award', 'photo', ]; public function educationalBackground() { return $this->belongsTo('App\Models\Users\EducationalBackground', 'educational_background_id'); } }
API路由
Route::get('/educational-background/{id}', [UserProfileController::class, 'getEducationalBackground']);
内容的提问来源于stack exchange,提问作者Kael
相关产品推荐
相关产品推荐

