【发布时间】:2020-05-29 16:46:04
【问题描述】:
我有两张桌子:
- 论坛帖子,结构:
+---------+---------+
| id | message |
+---------+---------+
- ForumPostVote,结构如下:
+---------+---------+---------+
| id | post_id | user_id |
+---------+---------+---------+
这是我的两个模型类:
- 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');
}
}
如您所见,在 ForumPost.php 中,我有一个函数 userVote(),我尝试从 ForumPostVote 中选择 id,其中用户 ID匹配登录用户。
当我提出请求时,它返回null。如果我删除->select('id'),它会正常返回对象:
"user_vote": {
"id": 1,
"post_id": 1,
"user_id": 1
}
如果我尝试类似:
public function userVote()
{
if (Auth::check())
{
$query = $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id);
return $query->id;
}
return null;
}
如果我这样做:
public function userVote()
{
if (Auth::check())
{
return $this->hasOne('App\ForumPostVote', 'post_id', 'id')->where('user_id', Auth::user()->id)->select(['id', 'post_id']);
}
return null;
}
这会返回:
"user_vote": {
"id": 1,
"post_id": 1
}
但这不是我想要的。我只想要id。
我做错了什么?
【问题讨论】:
-
尝试:->select('forumPostVotes.id');如果错误,请更正表名
-
@OMR 不幸的是,它仍在返回
null
标签: laravel laravel-5 eloquent