artyak
artyak

Reputation: 17

Laravel How to correctly select fields from multiple database tables?

I have a giveaway table, it has a winner_id column in which the user ID on the site is entered. It is necessary that the ID from the winner_id column looks in the users table and displays the user login that has found on the site. How can this be done correctly?

Upvotes: 0

Views: 38

Answers (1)

Chris Döhring
Chris Döhring

Reputation: 166

You are looking for a One to Many (inversed) relationship from the "Giveway" model side. First, you need to create a "Giveaway" model which represents your "giveaway" database table, in case you don't have that already. You should have the "user" model, as this exists by default. Your "giveaway" model could look like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Giveaway extends Model
{
    /**
     * Get the user that is related to the giveaway.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'id', 'winner_id');
    }
}

Now, get the giveaway instance and you can do something like this:

// this will print the user instance which is associated to the giveaway row with id #1
dd(Giveaway::find(1)->user);

For further details, please check the Laravel Docs: https://laravel.com/docs/6.x/eloquent-relationships#one-to-many-inverse

Upvotes: 2

Related Questions