【问题标题】:Eloquent hasMany filter and eager loadingEloquent 有很多过滤器和急切加载
【发布时间】:2017-10-25 14:07:48
【问题描述】:

我正在使用 Laravel 创建一个应用程序,并且我正在尝试使用 Eloquent。我有两个表:Orders 和 Items。

每个项目都有一个类型(int data):

  • 1 => 书
  • 2 => 视频

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

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

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();

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

谢谢

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

    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();
    

    【讨论】:

    • 嗨,Alexey,它适用于其他人,谢谢!但是对于书籍关系,我得到一个包含一个对象而不是直接对象的数组...
    • @D.Durand 我刚刚测试了它,你得到了一个对象。确保您使用的是hasOne 关系。要获得一本书,您仍然需要加载包含书籍和其他内容的订单集合并对其进行迭代。
    • 对不起,我用 hasMany 代替 hasOne !最后一个问题:为什么你说最好不要使用 where inside 关系?
    • @D.Durand 因为你会想要重用这些关系。如果您使用where 过滤数据,至少使用自定义名称,如bookTypeScifi
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多