vendredi 29 mai 2020

hasOne with select and where condition

I have two tables:

  1. ForumPost
+---------+---------+
|      id | message |
+---------+---------+
  1. ForumPostVote
+---------+---------+---------+
|      id | post_id | user_id |
+---------+---------+---------+

Here are my two model classes for each:

  1. ForumPost.php
class ForumPost extends Model
{
    protected $with = [
        'userVote'
    ];

    public function votes()
    {
        return $this->hasMany('App\ForumPostVote', 'post_id', 'id');
    }

    public function userVote()
    {
        if (Auth::check())
        {
            return $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id)->select('id');
        }

        return null;
    }
}
  1. ForumPostVote.php
class ForumPostVote extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function post()
    {
        return $this->belongsTo('App\ForumPost', 'id', 'post_id');
    }
}

As you can see, in ForumPost.php, I have a function userVote() where I try to to select the id from ForumPostVote where the user ID matches the logged in user.

However, it seems to be returning null, even though there is a record in the database. If I remove ->select('id') from the query, it returns fine, but it returns the whole object, when all I want is just the id.

What am I doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Xcvwjd
via IFTTT

Aucun commentaire:

Enregistrer un commentaire