[英]Extending models in Laravel Eloquent
在我的应用程序中,我有一个用户(废话)
class User {
public function teams()
{
return $this->belongsToMany(Team::class, 'team_user', 'user_id')->wherePivot('confirmed', '!=', null);
}
}
我正在尝试制作一个扩展User
的模型,就像这样
class Teamleader extends User
{
protected $table = 'users';
public static function boot()
{
parent::boot();
static::addGlobalScope(new TeamleaderScope);
}
}
这个想法是团队领导是一个用户,在team_user
数据透视表中将isLeader
布尔值设置为 true。 在我的TeamleaderScope
我尝试过类似的方法
class TeamleaderScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$model->teams()->wherePivot('isLeader', true);
}
}
但这似乎是错误的,因为Teamleader::all(
) 只是返回所有用户。 我从未尝试过扩展这样的模型,但应该是可能的,对吧? 任何人都可以在正确的方向上帮助我吗?
为了重用 PHP 中两个类中的公共方法等,您可以使用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
,你可以在使用它Teamleader.php
和使用的所有方法中Teamleader.php
。
例如,现在如果您想获得团队领导的用户,您可以尝试以下代码:
$leaders = User::Leaders();
$resultSearch = User::SearchLeaders("Gard Mikael");
我希望有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.