访问范围内的数据透视表

时间:2017-08-09 14:57:06

标签: php laravel eloquent

我花了近一个小时来解决这个问题。我有一个User模型和一个Event模型,与ManyToMany关系(代表一个邀请系统)相关联。我为枢轴类制作了一个模型:

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class Invitation extends Pivot
{
    const PENDING = 0;
    const ACCEPTED = 1;
    const UNCERTAIN = 2;
    const REFUSED = 3;
}

这是User型号:

class User extends Authenticatable
{
    // Deleted useless things

    public function events()
    {
        return $this->belongsToMany('App\Event')
                    ->using('App\Invitation')
                    ->withPivot('status')
                    ->withTimestamps();
    }
}

Event模型:

class Event extends Model
{
    public function guests()
    {
        return $this->belongsToMany('App\User')
                    ->using('App\Invitation')
                    ->withPivot('status')
                    ->withTimestamps();
    }

    /**
     * Return a list of guests who accepted the invitation.
     */
    public function scopeAccepted($query)
    {
        return $query->wherePivot('status', Invitation::ACCEPTED);
    }
}

虽然这句话很有效:
$event = Event::find(9)->guests()->wherePivot('status', Invitation::ACCEPTED)->get();

方法scopeAccepted给我这个错误:
Call to undefined method Illuminate\Database\Query\Builder::accepted()$event = Event::find(9)->guests()->accepted()->get();

。{

0 个答案:

没有答案