简体   繁体   中英

How to define the “follow” relationship in laravel 5.2

Recently I use Laravel to define the 'follow' relationship between users. Here are the models:

class User extends Model
{
    public function follows()
    {
        return $this->morphMany('App\User', 'followable');
    }
}

class Follow extends Model
{
    public function followable()
    {
        return $this->morphTo();
    }
}

and the database for Follow is like this:

follows:
    - id:
    - user_id:
    - followable_id:
    - followable_type:

all the above are defined according to the examples which Laravel documents provides.

And now I can retrieve the user model like this:

$follow = Follow:find(1);
$user = $follow->followable;

But when I write code like this:

$followers = $user->follows;

I get errors:

Relationship method must return an object of type 
Illuminate\Database\Eloquent\Relations\Relation

here is my question: Did I define the relationship of 'follow' right? and how can I fix the errors?

Thanks.

try this

class User extends Model
{
    public function follows()
    {
        return $this->morphMany('App\User', 'followable');
    }
}

change in to

    class User extends Model
{
    public function follows()
    {
        return $this->morphMany('App\Follow', 'followable');
    }
}

because your have given model name is incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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