更新的
用户模型
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");
}
}我有一个与User表相关的子表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");
}
}以及我想访问award字段的第三个表
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']);这是我的api方法,它工作得很好。但我想深入了解第三表的数据。
public function getEducationalBackground($id)
{
$educationalBackground = EducationalBackground::with('user')->where('user_id', $id)->get();
return response()->json($educationalBackground, 200);
}发布于 2022-07-25 08:54:44
看起来你还没有真正理解关系的概念。此外,我建议您研究路由模型绑定:)您基本上想要做的是:
public function getEducationalBackground($id)
{
$user = User::find($id);
return $user->educationalBackgrounds()->with('educationalAwards')->get();
}此外,当您非常确定无论何时您想要使用背景,您也想要使用奖励,您可以添加with(...)到模型定义如下:
class EducationalBackground extends Model
{
...
protected $with = ['educationalAwards'];
}这样,您可以将控制器方法简化为:
public function getEducationalBackground($id)
{
$user = User::find($id);
return $user->educationalBackgrounds;
}https://stackoverflow.com/questions/73106389
复制相似问题