如何在Laravel项目中联接的表中分离出ID [英] How can I separate out the Ids in tables joined within a Laravel Project

查看:90
本文介绍了如何在Laravel项目中联接的表中分离出ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下将3个表(图像,用户,个人资料)连接在一起的内容.我的问题是,以下结果仅给我1个id字段,也就是个人档案"表的ID.所有3个表都有其自己的ID字段.

I have the following that joins together 3 tables, Images, Users, Profiles. The problem I have is that the result of the following only gives me 1 id field and that is the Id of the Profiles table. All 3 tables have their own Id fields.

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

Can I seperate it so that it is images.id, profiles.id and users.id?

$images = \App\Image::where('image_approved', '=' ,"feature_approved")
            ->join('users', 'users.id', '=', 'images.user_id')
            ->join('profiles', 'profiles.user_id', '=', 'images.user_id')
            ->get();

推荐答案

您可以使用以下别名:

$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();

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

or you can simplify it by using Eloquent relationships.

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

So in your Image model you would have:

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

这篇关于如何在Laravel项目中联接的表中分离出ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆