首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得三级模型数据

如何获得三级模型数据
EN

Stack Overflow用户
提问于 2022-07-25 08:49:52
回答 1查看 59关注 0票数 1

更新的

用户模型

代码语言:javascript
复制
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

代码语言:javascript
复制
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字段的第三个表

代码语言:javascript
复制
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的路线

代码语言:javascript
复制
Route::get('/educational-background/{id}', [UserProfileController::class, 'getEducationalBackground']);

这是我的api方法,它工作得很好。但我想深入了解第三表的数据。

代码语言:javascript
复制
public function getEducationalBackground($id) 
    {
        $educationalBackground = EducationalBackground::with('user')->where('user_id', $id)->get();

        return response()->json($educationalBackground, 200);
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-25 08:54:44

看起来你还没有真正理解关系的概念。此外,我建议您研究路由模型绑定:)您基本上想要做的是:

代码语言:javascript
复制
public function getEducationalBackground($id) 
{
    $user = User::find($id);
    return $user->educationalBackgrounds()->with('educationalAwards')->get();
}

此外,当您非常确定无论何时您想要使用背景,您也想要使用奖励,您可以添加with(...)到模型定义如下:

代码语言:javascript
复制
class EducationalBackground extends Model
{
    ...
    protected $with = ['educationalAwards'];
}

这样,您可以将控制器方法简化为:

代码语言:javascript
复制
public function getEducationalBackground($id) 
{
    $user = User::find($id);
    return $user->educationalBackgrounds;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73106389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档