【问题标题】:get() method is not working with eloquent relationships Laravel 5get() 方法不适用于雄辩的关系 Laravel 5
【发布时间】:2015-08-23 12:12:49
【问题描述】:

我有一个用户模型和一个朋友模型。在用户模型中我有

public function friends(){
        return $this->hasMany('App\FacebookModels\Friend' ,'user_id');
    }

在朋友模型中我有

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

我想检索用户的关注者,这就是我正在尝试的

    public function listFollowers($id,$name){

//user_id = 1 and there are two rows in table friends for user_id 1
            $user_id = $_SERVER['REQUEST_URI'];
            $user_id =  preg_replace("/[^0-9]/","",$user_id);
            $followers = Friend::where('user_id',$user_id)->get();
            foreach($followers->user as $user){
                echo $user->name;
            }
        }

但我收到以下错误。

ErrorException in FacebookPagesController.php line 65:
Undefined property: Illuminate\Database\Eloquent\Collection::$user

行号65

foreach($followers->user as $user)

但是当我将get() 更改为first() 我收到以下错误

ErrorException in FacebookPagesController.php line 66:
Trying to get property of non-object

第 66 行是

echo $user->name;

但是,这适用于first()

echo $followers->user->name;

我无法理解这之间的区别以及为什么这不起作用。如果你能解释清楚,那对大多数人来说都很棒。 这是我的friends table

Schema::create('friends', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('follower')->unsinged();
            $table->timestamps();
        });

这是users table

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });

【问题讨论】:

    标签: eloquent laravel-5.1


    【解决方案1】:

    first() 返回一个 model 实例,而 get() 返回一个模型的 collection

    因此,如果您想使用first(),您应该使用getAttribute 方法从您的$user 获取属性/属性。

    例子:

    $name = $user->getAttribute('name');
    

    【讨论】:

    • 但我想使用 get() 因为我的查询返回多个结果。
    • 尝试foreach($followers as $follower) 并在循环内$follower->user->name
    • 我有个问题,知道解决办法的请回答link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2019-05-22
    • 2015-12-17
    • 2017-08-22
    相关资源
    最近更新 更多