简体   繁体   English

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

[英]Laravel call to a member function addEagerConstraints() on boolean

I'm getting the following error whenever i go on to a users page, its supposed to show if the authenticated user is already following the user that the profile is on. 每当我转到用户页面时,都会出现以下错误,该错误应该显示是否通过身份验证的用户已经在关注配置文件所在的用户。

Could this be a problem with the relationship setup, it hasMany 难道这是有关系的设置有问题,它hasMany

Stack trace 堆栈跟踪

local.ERROR: Call to a member function addEagerConstraints() on boolean {"userId":1,"email":"fakeemail@aol.com","exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function addEagerConstraints() on boolean at /Applications/MAMP/htdocs/elipost/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:522)"} [] local.ERROR:在布尔值{“ userId”:1,“ email”:“ fakeemail@aol.com”,“ exception”:“ [对象](Symfony \\ Component \\ Debug \\ Exception \\中,调用成员函数addEagerConstraints() FatalThrowableError(code:0):在/Applications/MAMP/htdocs/elipost/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:522上的布尔值上调用成员函数addEagerConstraints() ]

UserController.php 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(model) 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();
    }


}

MyFollow MyFollow

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


}

Post 岗位

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






}

Likes 喜欢

<?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'
    ];



}

User(model) 用户(模型)

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




}

As Jonas Staudenmeir stated, followedByMe isn't a relationship, it's a regular function and what it does is returning a boolean. 正如Jonas Staudenmeir所说,followByMe不是关系,它是一个常规函数,它的作用是返回布尔值。 I'm confused at why you've got a follow on your user model and trying to get information from the follow's follower? 我对为什么要在用户模型上关注并为什么要从关注者那里获取信息感到困惑? Just simplify, I see too much unneeded eager loading here. 简化一下,我在这里看到了太多不必要的渴望加载。

Searching by indexed elements (id) > searching by name, any day of the week 按索引元素(id)搜索>按名称搜索,一周中的任意一天

Edit: 编辑:

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

User Model 用户模型

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

Post Model 邮政模型

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

MyFollow Model MyFollow模型

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

With the help of @abr i found a simple fix, simple solution. 在@abr的帮助下,我找到了一个简单的解决方案。

MyFollow.php(model) 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(model) 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 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);
    }

it works now. 现在有效。 :) :)

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

相关问题 在字符串上调用成员函数 addEagerConstraints() - Laravel 8 - Call to a member function addEagerConstraints() on string - Laravel 8 在float LARAVEL上调用成员函数addEagerConstraints() - Call to a member function addEagerConstraints() on float LARAVEL Laravel-在字符串上调用成员函数addEagerConstraints() - Laravel - Call to a member function addEagerConstraints() on string Laravel 调用成员 function addEagerConstraints() on float - Laravel call to a member function addEagerConstraints() on float 在 null 上调用成员 function addEagerConstraints() - Call to a member function addEagerConstraints() on null 在字符串上调用成员函数 addEagerConstraints() - Call to a member function addEagerConstraints() on string Laravel 5 查询关系导致“调用成员函数 addEagerConstraints() on null”错误 - Laravel 5 Querying with relations causes "Call to a member function addEagerConstraints() on null" error 在 null 上调用成员函数 addEagerConstraints() 在 laravel 6 上出现此错误 - Call to a member function addEagerConstraints() on null getting this error on laravel 6 我在 integer 上收到对成员 function addEagerConstraints() 的错误调用 - I get The Error Call to a member function addEagerConstraints() on integer 由于条件关系,在 null 上调用成员函数 addEagerConstraints() - Call to a member function addEagerConstraints() on null because of a conditional relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM