laravel使用范围方法

时间:2017-05-29 10:10:57

标签: php laravel scope

我正在尝试学习laravel范围,我创建了我的第一个范围,但我收到此错误信息npw

Support.php第26行中的ErrorException: 未定义的属性:Illuminate \ Database \ Eloquent \ Builder :: $ User

这就是

public static function getTicket($id)
{
    $ticket = Support::where('id', $id)->User::owner(Auth::user()->id)->first();
    return $ticket;
}

,这是用户模型

public function scopeOwner($query, $flag)
{
    return $query->where('user_id', $flag);
}

用户与支持之间的关系

public function user()
{
    return $this->belongsTo('App\User');
}

你能告诉我,我做错了什么吗?

2 个答案:

答案 0 :(得分:1)

删除"用户::"像这样:

public static function getTicket($id)
{
    $ticket = Support::where('id', $id)->owner(Auth::user()->id)->first();
    return $ticket;
}

然后将函数scopeOwner从用户模型移动到支持模型。

答案 1 :(得分:1)

您正在使用范围错误。范围应该在您希望使用它的模型中。所以将它移到Support模型。

public function scopeOwner($query, $id)
{
    return $query->where('user_id', $id);
}

public static function getTicket($id)
{
    $ticket = Support::where('id', $id)->owner(Auth::user()->id)->first();

    return $ticket;
}

你也可以这样做

public static function getTicket($id)
{
    $ticket = static::where('id', $id)->owner(auth()->id())->first();

    return $ticket;
}