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?
-
Need more info - note (in detail) how to reproduce the problem. What you are looking for and why it is not what you expected.Casey Harrils– Casey Harrils2020-01-21 22:46:02 +00:00Commented Jan 21, 2020 at 22:46
Add a comment
|
1 Answer
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