Как я могу выделить идентификаторы в таблицах, объединенных в Laravel Project? - PullRequest
0 голосов
/ 18 июня 2019

У меня есть следующее, что объединяет 3 таблицы, изображения, пользователи, профили.Проблема, которую я имею, состоит в том, что результат следующего дает мне только 1 поле идентификатора, и это Id таблицы профилей.Все 3 таблицы имеют свои собственные поля Id.

Можно ли разделить его так, чтобы это были images.id, profiles.id и 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();

Ответы [ 2 ]

1 голос
/ 19 июня 2019

Используйте псевдоним для выбора следующим образом:

->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();
1 голос
/ 18 июня 2019

Вы можете использовать их псевдонимы следующим образом:

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

или вы можете упростить их, используя отношения Eloquent.

Таким образом, в вашей модели 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...