首页 > 解决方案 > Laravel - 在 laravel 模型中返回关系数组

问题描述

我想在我的服务关系中返回一个数组。在我的输出中,我想要类似的东西:

services: {
 true: {...},
 false: {...},
}

它本身的关系正在发挥作用。如果我只是

return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 1)

然后它工作正常。但我想更深入。我希望 services 方法返回一个带有 false 和 true 键的数组。

像这儿:

public function services()
    {
        return [
            "true" => $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 1),
            "false" => $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 0)
        ];
    }

但我得到的是:

错误:调用数组上的成员函数 addEagerConstraints()

标签: laravellaravel-5eloquent

解决方案


我认为您在第二种方法中以错误的方式使用了 laravel 的关系功能。

例如,您可以在模型上定义两个关系函数,如下所示:

public function servicesIncluded()
{
    return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
        ->wherePivot('includes_it', 1);
}

public function services()
{
    return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
        ->wherePivot('includes_it', 0);
}

然后你可以做这样的事情(假设你的模型被称为产品):

$products_included = Product::servicesIncluded()->get();
$prodcuts_excluded = Product::services()->get();
$result = [
    "true" => $products_included,
    "false" => $products_excluded
];

或者您可以像这样在您的关系中包含数据透视列:

public function services()
{
    return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
        ->withPivot('includes_it');
}

推荐阅读