Laravel 拉维关系误差

Laravel 拉维关系误差,laravel,Laravel,我在获取数据库的数据时遇到问题。 我有两个模型,用户,追随者 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Follower extends Model { public function mentor() { return $this->belongsTo('App\User','id

我在获取数据库的数据时遇到问题。 我有两个模型,用户,追随者

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

    class Follower extends Model

        {
            public function mentor()
            {
                return $this->belongsTo('App\User','id','mentor_id');
            }
            public function follower()
            {
                return $this->belongsTo('App\User','id','user_id');
            }
        }

<?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Friend;
use App\Follower;

class User extends Model implements Authenticatable
{
public function followers()
   {
       return $this->hasMany('App\Follower','mentor_id','id');
   }

   public function follows()
   {
       return $this->hasMany('App\Follower','user_id','id');
   }
}

你把这件事复杂化了。您只需要一个数据透视表来保存追随者信息

在透视表之后添加

Schema::create('follows', function (Blueprint $table) {
    $table->unsignedInteger('follower_id');
    $table->unsignedInteger('followed_id');
    $table->timestamps();

    $table->primary(['follower_id', 'followed_id']);

    $table->foreign('follower_id')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');

    $table->foreign('followed_id')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');
});
将此添加到
用户
模型

public function following()
{
    return $this->belongsToMany(User::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}

public function followers()
{
    return $this->belongsToMany(User::class, 'follows', 'followed_id', 'follower_id')->withTimestamps();
}
在控制器中执行此操作

public function getFollows()
{
    $follows = auth()->user()->following;
    return view('follows', ['follows' => $follows]);
}

public function getFollowers()
{
    $followers = auth()->user()->followers;
    return view('followers', ['followers' => $followers]);
}
我基于在我的一个OSS项目中实现的follow特性的代码。您可以查看它以了解更多信息


注意:不需要为透视表定义模型。您正在从用户模型关系中获取关注者和以下信息。

用户表中没有
mentor\u id
(外键)。首先定义它
Schema::create('followers.blade.php',function(Blueprint$table)
what?ok失败,稍等一会我会更正ok,我更改了,但它不工作,反正是同一个问题
public function following()
{
    return $this->belongsToMany(User::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}

public function followers()
{
    return $this->belongsToMany(User::class, 'follows', 'followed_id', 'follower_id')->withTimestamps();
}
public function getFollows()
{
    $follows = auth()->user()->following;
    return view('follows', ['follows' => $follows]);
}

public function getFollowers()
{
    $followers = auth()->user()->followers;
    return view('followers', ['followers' => $followers]);
}