Eloquent hasMany 过滤器和预先加载

Eloquent hasMany filter and eager loading

我正在使用 Laravel 创建一个应用程序,我正在尝试使用 Eloquent。我有两个表:订单和项目。

每个项目都有一个类型(整数数据):

每个订单都有一本书和很多视频。

在我的订单模型中,我想要一本书和其他物品之间的关系。所以,我有这个代码:

public function book()
{
    return $this->hasMany('App\Item')->where('type', 1)->first();
}

public function others()
{
    return $this->hasMany('App\Item')->where('type', '!=', 1)->get();
}

但是,如果我对我的关系使用预先加载,我会收到错误消息:

Order::with(['book', 'others'])->get();

你能帮我解决这个问题吗?

谢谢

像这样定义关系以使您的代码工作:

public function book()
{
    return $this->hasOne('App\Item')->where('type', 1);
}

public function others()
{
    return $this->hasMany('App\Item')->where('type', '!=', 1);
}

但最好在没有 where 约束的情况下定义关系:

public function book()
{
    return $this->hasOne('App\Item');
}

public function others()
{
    return $this->hasMany('App\Item');
}

然后这样做:

Order::with(['book' => function ($q) {
        $q->where('type', 1);
    },
    'others' => function ($q) {
        $q->where('type', '!=', 1);
    }])
    ->get();