【问题标题】:I want to return a user with a list of all the people they have referred by there username我想返回一个用户,其中列出了他们通过该用户名推荐的所有人员的列表
【发布时间】:2020-08-01 00:23:41
【问题描述】:

我正在我的软件中开发推荐系统。我已获得推荐权,但我想列出 auth 用户推荐的所有用户。

注意:我正在编写一个 API 端点,所以我不能使用关系来显示他们的名字。 这是我的用户模型

public function referrals()
{
    return $this->hasMany(Referral::class, 'user_id', 'id');
}

public function referrer()
{
    return $this->hasOne(Referral::class, 'referred_by', 'id');
}

注意:refered_by 是推荐人,user_id 是被推荐人

这是我的推荐模型

protected $fillable = ['user_id', 'referred_by', 'status'];

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

这是我的推荐迁移

Schema::create('referrals', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned()->references('id')->on('users');
            $table->integer('referred_by')->unsigned()->references('id')->on('users');
            $table->string('status')->nullable();
            $table->timestamps();
        });

【问题讨论】:

  • 您为什么不直接编辑users 表并添加referred_bystatus?我对你的referrals 表结构感到很困惑

标签: laravel


【解决方案1】:

用户模型

// Referrals given by the user.
public function referralsGiven()
{
    return $this->hasMany(App\Referral::class, 'referred_by', 'id');
}

推荐模型

//Person who got the referral
public function user()
{
    return $this->belongsTo(App\User::class, 'user_id', 'id');
}

public function referredBy()
{
    return $this->belongsTo(App\User::class, 'referred_by', 'id');
}

采摘方式https://laravel.com/docs/7.x/collections#method-pluck

控制器

$user = User::with('referralsGiven.user')->find(Auth::user()->id);

$users_reffered_by_Auth_user = $user->referralsGiven->pluck('user');

$referrals = Referral::with('user')->where('reffered_by', Auth::user()->id)->get();

$users_reffered_by_Auth_user = $referrals->pluck('user');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2018-08-27
    • 2014-06-01
    • 1970-01-01
    • 2012-10-30
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多