简体   繁体   English

与用户条件的关系

[英]Relationship with user condition

I have a follow system that works like Twitter's follow (you follow other people and get updates from them). 我有一个关注系统,其工作方式类似于Twitter的关注(您关注其他人并从他们那里获取更新)。

I have this relationship set in my User.php model: 我在User.php模型中设置了以下关系:

public function follows()
{
    return $this->hasMany('App\Follow');
}

This obviously gets all records of users who follow this person. 显然,这会获得关注此人的用户的所有记录。

However, when displaying the person's profile page, I want to get a relationship that checks if a follow record exists given the user ID. 但是,当显示此人的个人资料页面时,我想获得一种关系,该关系检查在给定用户ID的情况下是否存在关注记录。

Something like: 就像是:

public function userFollow()
{
    return $this->hasOne('App\Follow')->where('user_id', Auth::user()->id);
}

So now my profile page query looks like this: 所以现在我的个人资料页面查询看起来像这样:

$user = User::where('username', $username)
    ->with('userFollow')
    ->first();

This works as long as the user is logged in. If the user isn't logged in, the page gives me this error: 这只要用户登录工作。如果用户没有登录,页面给我这个错误:

ErrorException in User.php line 28: Trying to get property of non-object User.php第28行中的ErrorException:尝试获取非对象的属性

How do I fix this? 我该如何解决? What is the proper way of using conditions in relationships? 在关系中使用条件的正确方法是什么?

This is because if user is logged out then Auth::user() is null, because user session has ended. 这是因为如果用户注销,则Auth :: user()为null,因为用户会话已结束。 Auth::user() is no more object, so you can't get the id from a null object. Auth :: user()不再是对象,因此您无法从空对象获取ID。

Here you can do something like that 在这里你可以做这样的事情

public function userFollow()
{
  $userId = Auth::user() ? Auth::user()->id : $this->id; 
  return $this->hasOne('App\Follow')->where('user_id', $userId);
}

then it will not look for authenticated user, it will just get the particular user table's id. 那么它将不会查找经过身份验证的用户,而只会获取特定用户表的ID。

The proper way of using conditions in relationships is using Constraining eager loads 在关系中使用条件的正确方法是使用约束急切负载

public function userFollow()
{
    return $this->hasOne('App\Follow');
}

And, 和,

if(Auth::check())
{
       $user = User::where('username', $username)
             ->with(['userFollow'=>function($query)
                {
                    $query->where('user_id', Auth::user()->id);
                }]);
             ->first();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM