Laravel在布尔值上调用成员函数addEagerConstraints()

时间:2018-07-09 21:15:58

标签: php laravel

每当我转到用户页面时,我都会收到以下错误消息,它应该显示经过身份验证的用户是否已经在关注该个人资料所在的用户。

这可能是关系设置方面的问题吗,hasMany

堆栈跟踪

  

local.ERROR:调用成员函数addEagerConstraints()   布尔值{“ userId”:1,“电子邮件”:“ fakeemail@aol.com”,“例外”:“ [对象]   (Symfony \ Component \ Debug \ Exception \ FatalThrowableError(代码:0):   在boolean上调用成员函数addEagerConstraints()   /Applications/MAMP/htdocs/elipost/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:522)“}   []

UserController.php

public function getProfile($user)
{  
    $users = User::with([
        'posts.likes' => function($query) {
            $query->whereNull('deleted_at');
            $query->where('user_id', auth()->user()->id);
        },
        'follow',
        'follow.follower'
    ])->with(['followers' => function($query) {
        $query->with('follow.followedByMe');
        $query->where('user_id', auth()->user()->id);
    }])->where('name','=', $user)->get();

    $user = $users->map(function(User $myuser){
        return ['followedByMe' => $myuser->followers->count() == 0];
    });


    if (!$user) {
        return redirect('404');
    }

    return view ('profile')->with('user', $user);
}

MyFollow(模型)

<?php

class MyFollow extends Model
{
    use SoftDeletes, CanFollow, CanBeFollowed;

    protected $fillable = [
        'user_id',
        'followable_id'
    ];

    public $timestamps = false;

    protected $table = 'followables';

    public function follower()
    {
        return $this->belongsTo('App\User', 'followable_id');
    }

    public function followedByMe()
    {
      return $this->follower->getKey() === auth()->id();
    }


}

我的关注

use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;

class MyFollow extends Model
{
    use SoftDeletes, CanFollow, CanBeFollowed;

    protected $fillable = [
        'user_id',
        'followable_id'
    ];

    public $timestamps = false;

    protected $table = 'followables';

    public function follower()
    {
        return $this->belongsTo('App\User', 'followable_id');
    }

    public function followedByMe()
    {
      return $this->follower->getKey() === auth()->id();
    }


}

发布

class Post extends Authenticatable
{


    protected $fillable = [
        'title',
        'body',
        'user_id',
        'created_at',

    ];


    public function user()
    {
        return $this->belongsTo(User::class);
    }

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

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

    public function likedByMe()
    {
        foreach($this->likes as $like) {
            if ($like->user_id == auth()->id()){
                return true;
            }
        }
        return false;
    }






}

喜欢

<?php

namespace App;

use App\Post;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Like extends Model
{
    use SoftDeletes;

     protected $fillable = [
        'user_id',
        'post_id'
    ];



}

用户(型号)

class User extends Authenticatable
{
    use Notifiable,CanFollow, CanBeFollowed;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function posts()
    {
        return $this->hasMany(Post::class);

    }


    public function images()
    {
        return $this->hasMany(GalleryImage::class, 'user_id');

    }


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

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



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




}

2 个答案:

答案 0 :(得分:1)

正如Jonas Staudenmeir所说,followByMe不是关系,它是一个常规函数,它的作用是返回布尔值。我对为什么要在用户模型上关注并为什么要从关注者那里获取信息感到困惑?简化一下,我在这里看到了太多不必要的渴望加载。

  

按索引元素(id)搜索>按名称搜索,一周中的任意一天

编辑:

UserController

public function getProfile(Request $request, $id)
{  
    //$request->user() will get you the authenticated user
    $user = User::with(['posts.likes','followers','follows','followers.follows'])
    ->findOrFail($request->user()->id);
    //This returns the authenticated user's information posts, likes, followers, follows and who follows the followers 
    //If you wish to get someone else's information, you just switch 
    //the $request->user()->id to the $id if you're working with id's, if you're
    //working with names, you need to replace findOrFail($id) with ->where('name',$name')->get() and this will give you
    //a collection, not a single user as the findOrFail. You will need to add a ->first() to get the first user it finds in the collection it results of
    //If you're planning on getting an attribute (is_following = true) to know if
    //the authenticated user is following, you can use an accessor in the User model and write this after you've fetched the instance of the User
    //$user->append('is_following');
    return view ('profile')->with('user', $user);
}

用户模型

//Accessor
//People who this user follows
public function getIsFollowingAttribute()
{   
    return MyFollow::where('followable_id',$this->attributes['id'])->where('user_id',Auth()->user()->id)->count() > 0 ? true : false;
}
//Relationships
//People who this user follows
public function follow()
{   
    return $this->hasMany('App\MyFollow','user_id','id');
}
//People who follows this user
public function followers()
{   
    return $this->hasMany('App\MyFollow','followable_id','id');
}
//Posts of this user
public function posts()
{   
    return $this->hasMany('App\Post','user_id','id');
}
//Likes of this user, not sure about this one tho, we're not using this for now but it could come in handy for you in the future
public function likes()
{   
    return $this->hasManyThrough('App\Likes','App\Post','user_id','user_id','id');
}

发布模型

//Who like this post
public function likes()
{   
    return $this->hasMany('App\Post','user_id','id');
}

我的关注模型

//Relationships
//People who follow this user
public function followers()
{   
    return $this->hasMany('App\MyFollow','followable_id','user_id');
}
//Relationships
//People who this user follows
public function follow()
{   
    return $this->hasMany('App\MyFollow','user_id','followable_id');
}

答案 1 :(得分:0)

在@abr的帮助下,我找到了一个简单的解决方案,简单的解决方案。

MyFollow.php(模型)

public function followers()
{   
    return $this->hasMany('App\MyFollow','followable_id','user_id');
}
//Relationships
//People who this user follows
public function follow()
{   
    return $this->hasMany('App\MyFollow','user_id','followable_id');
}

User.php(模型)

public function getIsFollowingAttribute()
{   
    return MyFollow::where('followable_id',$this->attributes['id'])->where('user_id',Auth()->user()->id)->count() > 0 ? true : false;
}


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

UserController.php

 public function getProfile($user)
    {  
        $users = User::with(['posts.likes' => function($query) {
                            $query->whereNull('deleted_at');
                            $query->where('user_id', auth()->user()->id);
                        }, 'followers','follow.followers'])

                        ->with(['followers' => function($query) {


                        }])->where('name','=', $user)->get();

        $user = $users->map(function(User $myuser){

            $myuser['followedByMe'] = $myuser->getIsFollowingAttribute();

            return $myuser;
        });


        if(!$user){
            return redirect('404');
        }

        return view ('profile')->with('user', $user);
    }

现在可以使用。 :)