I have two tables:
- ForumPost
+---------+---------+
| id | message |
+---------+---------+
- ForumPostVote
+---------+---------+---------+
| id | post_id | user_id |
+---------+---------+---------+
Here are my two model classes for each:
- 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;
}
}
- 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