如何在Laravel项目中联接的表中分离出ID

时间:2019-06-18 19:35:59

标签: php laravel orm

我有以下将3个表(图像,用户,个人资料)连接在一起的文件。我的问题是,以下结果仅给我1个ID字段,也就是“个人档案”表的ID。这3个表都有自己的ID字段。

我可以将其分开以使其是images.id,profiles.id和users.id吗?

Request.UserHostAddress

2 个答案:

答案 0 :(得分:1)

您可以像这样对它们起别名:

$images = \App\Image::select([
                'users.id as user_id',
                'profiles.id as profile_id',
                'images.id as image_id',
                //... add the rest of the columns that you want to select here.
            ])
            ->where('image_approved', '=' ,"feature_approved")
            ->join('users', 'users.id', '=', 'images.user_id')
            ->join('profiles', 'profiles.user_id', '=', 'images.user_id')
            ->get();

或者您可以通过雄辩的关系来简化它。

因此,在您的Image模型中,您将拥有:

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

public function profile()
{
    return $this->hasOneThrough(Profile::class, User::class);
}

然后您可以检索它们:

$images = Image::with('user', 'profile')
               ->where('image_approved', '=' ,"feature_approved")
               ->get();

// now each $image in $images will have user and profile relationship

// $image->id
// $image->user->id
// $image->profile->id

答案 1 :(得分:1)

像这样在选择中使用别名:

->join('profiles', 'profiles.user_id', '=', 'images.user_id')
->select('images.*', 'users.*', 'profiles.*', 'images.id as imageID', 'profiles.id as profileId', 'users.id as usersId')
->get();