【问题标题】:hasOne() with select and where conditionhasOne() 带有 select 和 where 条件
【发布时间】:2020-05-29 16:46:04
【问题描述】:

我有两张桌子:

  1. 论坛帖子,结构:
+---------+---------+
|      id | message |
+---------+---------+
  1. ForumPostVote,结构如下:
+---------+---------+---------+
|      id | post_id | user_id |
+---------+---------+---------+

这是我的两个模型类:

  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');
    }
}

如您所见,在 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


【解决方案1】:

如果我对您的理解正确,您在 ForumPost 和用户之间有很多对多的关系......并且数据透视表是 ForumPostVote

1- forumPostVote 必须继承自 Pivot 而不是模型。

https://laravel.com/docs/7.x/eloquent-relationships#defining-custom-intermediate-table-models

2-如果要获取当前用户的数据透视表的id:

public function userVote()
{
    if (Auth::check())
    {
$value=$this->votes()->where('user_id',Auth::user()->id)->first();
if($value!=null) return $value->id;
        return value;
    }

    return null;
}

请注意,如果 ForumPostVote 表中没有对应的 id,则结果将为空

【讨论】:

    猜你喜欢
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2012-08-14
    • 2013-04-08
    相关资源
    最近更新 更多