Laravel模型未定义的关系问题仅在$with变量中

3df52oht  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(80)

我在Laravel 8.47.0项目中遇到了一个以前从未遇到过的特殊问题。当我在Order模型的$with变量中包含'events'关系时,问题出现了。错误消息指出“Undefined relationship [events]"。
然而,当我获取API响应时,关系似乎无缝加载,没有任何问题。此外,这个问题在我的本地机器或测试服务器上没有复制。
我试图确保Order模型中的关系定义正确,如“events”函数中所示。通过API检索时,关系似乎正常工作。
我附上了相关的代码片段以供参考:
下面是代码:

class Order extends BaseModel
{
    use PowerJoins, HasStatuses;
    protected $with = ['user', 'driver', 'statuses', 'taxi_order']; // The issue arises when 'events' is added here.
    // ... (other code)

字符串
关系定义:

public function events()
{
    return $this->hasMany('App\Models\OrderEvent', 'order_id', 'id');
}


我一直无法确定这个问题的根本原因,这对我来说已经成为一个令人困惑的情况。这是我使用Laravel的经验中第一次遇到这样奇怪的问题。
以前有没有人遇到过类似的问题?任何关于如何解决这个问题的见解或建议都将不胜感激。
提前感谢您的帮助!

xjreopfe

xjreopfe1#

我将在这里定义关系式并假设
你有一个表order_events,它有一个名为order_id的外部列,对吗?

// Order.php

use App\Models\OrderEvent;

public function events()
{
    return $this->hasMany(OrderEvent::class, 'order_id', 'id');
}

个字符
你那边是这样的吗?

z9gpfhce

z9gpfhce2#

显然,在你的Laravel模型中创建一个包含$query->with()的作用域会影响你的protected $with = []。这对我来说是一个教训。你需要确保如果你的代码使用了你的模型的作用域,你也需要在那里包含关系,因为$query->with()似乎覆盖了你在protected $with = []中定义的急切加载。在我的例子中,这是我必须做的

public function scopeFullData($query, $extraWiths = []) {
        $fixedWiths = [
            "products.product", "stops.delivery_address", "user", "driver.vehicle", "delivery_address", "payment_method", "vendor" => function ($query) {
                return $query->withTrashed();
            }, 'package_type', "taxi_order.waypoints", "events" /* added "events" here */
        ];

        $withs = array_merge($fixedWiths, $extraWiths);
        return $query->with($withs);
}

字符串

相关问题