gpt4 book ai didi

php - 在 Laravel Eloquent 中扩展模型

转载 作者:行者123 更新时间:2023-12-01 16:35:54 26 4
gpt4 key购买 nike

在我的应用程序中,我有一个用户(废话)

class User {

public function teams()
{
return $this->belongsToMany(Team::class, 'team_user', 'user_id')->wherePivot('confirmed', '!=', null);
}
}

我正在尝试创建一个扩展用户的模型,就像这样

class Teamleader extends User
{
protected $table = 'users';

public static function boot()
{
parent::boot();

static::addGlobalScope(new TeamleaderScope);
}
}

这个想法是,团队领导者是 team_user 数据透视表中的 isLeader bool 值设置为 true 的用户。在我的 TeamleaderScope 中,我已经尝试过类似的事情

class TeamleaderScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$model->teams()->wherePivot('isLeader', true);
}
}

但这似乎是错误的,因为 Teamleader::all() 仅返回所有用户。我从未尝试过扩展这样的模型,但这应该是可能的,对吗?谁能帮助我朝正确的方向前进?

最佳答案

为了重用PHP中两个类中的公共(public)方法等,可以使用trait。在您的情况下,在其余模型旁边创建一个 php 文件,我将其命名为 CommonTrait.php ,其内部必须如下所示:

<?php

namespace App;


trait CommonTrait
{
public function commonMethodOne()
{
// anything
}

public function commonMethodTwo()
{
// anything
}

// for get leaders.
public function scopeLeaders()
{
return $this->teams()->wherePivot('isLeader', true);
}

public function scopeSearchLeaders($query, $keyword)
{
return $query->where('name', $keyword)->wherePivot('isLeader', true);
}


}

所以现在您可以在任何您想要的地方使用trait

例如,在User.php中使用它:

<?php

namespace App;

class User
{
use CommonTrait;
}

所以,现在 CommonTrait.php 中的所有方法或变量都可以在 User.php 中访问,并且您可以使用 User.php 中的那些方法或变量code>,您可以在 Teamleader.php 中使用它,并在 Teamleader.php 中使用它的所有方法。
例如,现在如果你想获得团队领导者的用户,你可以尝试以下代码:

$leaders = User::Leaders();
$resultSearch = User::SearchLeaders("Gard Mikael");

希望对你有用

关于php - 在 Laravel Eloquent 中扩展模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60570552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com