Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shan11's avatar

Get number of position from net votes

I have two tables (users, votes)

users table

| id  | name |
| --- | -------|
| 1    | Ida    |
| 2   | Boo   |
| 3   | Lala   |
| 4   | Bash  |

votes table

| id   |  user_id     |    net_votes |
--------------------------------------
| 1         1             5000         

| 2        2              2000         

| 3        3              5000          

| 4        4              0               

=========================

I want to get the result like this (using laravel Eloquent method)


| name       |  net_votes  |      position  |
----------------------------------------------
Ida              5000                1      

Lala             5000                1      

Boo              2000                2      

Bash            0                    3      


Can anyone help on this?

Thanks

0 likes
6 replies
tisuchi's avatar

ok, try like this way-

In user model-

public function votes()
    {
        return $this->hasOne('App\Vote', 'user_id');
    }

In vote model-

public function user()
    {
        return $this->belongsTo('App\User');
    }

Now in your controller, you can try with-

$user = User::get();
return view('your-view-page')->with('users', $users);

Now, in your view, use like this way-

<table>
    <tr>
        <td>Name</td>
        <td>Net Votes</td>
        <td>Position</td>
    </tr>
    @foreach($users as $user)
    <tr>
        <td>{{ $user->name }} </td>
        <td> {{ $user->votes->net_votes }} </td>
        <td> {{ $user->votes->position }} </td>
    </tr>
    @endforeach



</table>

Ref: https://laravel.com/docs/5.3/eloquent-relationships#one-to-one

shan11's avatar

Hi @tisuchi Thanks for the reply. I want to get number of position from net votes. for your better read, I have edited my question.

shan11's avatar

@tisuchi

in votes table do not have position column. we need to calculate position automatically from net votes. if user got higher votes, position will come as 01. if two users got same votes, position will come as same position.

tisuchi's avatar

I see....

If I am right, you can not do that in eloquent relationship. You need to take help from queries. Here is the link- https://laravel.com/docs/5.3/queries#joins

You may need to use join. That may help you-

$users = DB::table('users')
            ->join('votes', 'users.id', '=', 'votes.user_id')
            ->select('users.*', 'votes.*')
            ->select('votes.net_votes', DB::raw('count(*) as total'))
            ->orderBy('total', 'desc')
            ->get();
1 like
shan11's avatar

Ok. @tisuchi I am already using query. reason for asked laravel method, there are some other tables also joint with votes table. so , it will be easy if I use eloquent method.

Thank you

Please or to participate in this conversation.