我花了近一个小时来解决这个问题。我有一个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();