繁体   English   中英

laravel 如何通过另一个 model 访问 model 的数据

[英]laravel how I can access data of model through another model

我正在使用 laravel 8 并且我具有以下表结构。

用户表

id,name,email,password,...等。

用户资料表

id,bio,facebook,twitter,phone,user_id,...等。

项目表

id, title, details, image, user_id,....等。

我在项目 model 中创建了以下关系

public function user(){
    return $this->belongsTo(User::class,'user_id');
}

并且在用户 model 中有另一个关系如下

 public function profile(){
    return $this->hasOne(UserProfile::class,'user_id');
}

我的问题是如何通过项目 model 访问用户配置文件? 我阅读了 hasOneThrough 关系,但我不明白如何在我的代码中应用它

首先,您需要获得一个用户,然后您才能访问该配置文件。 所以:

Project::with('user.profile')->get()

假设在您的user_profiles表中您有project_id作为外键,请尝试:

public function userProfile()
    {
        return $this->hasOneThrough(
           UserProfile::class,
           Project::class,
           'user_id', // Foreign key on the projects table
           'project_id', // Foreign key on the user_profiles table
           'id', // Local key on the users table
           'id' // Local key on the projects table
    );
    }

改变这个:

public function profile(){
    return $this->hasOne(UserProfile::class,'user_id');
}

对此:

public function profile(){
    return $this->belongsTo(UserProfile::class,'user_id');
}

将此添加到您的用户配置文件 model 中:

public function user(){
    return $this->hasOne(User::class);
}

获取项目并尝试检查是否有效:

$project->user->profile;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM