laravel - 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()
解决方案
我认为您在第二种方法中以错误的方式使用了 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');
}
推荐阅读
- java - Sprinboot 1.4.0,是否可以在启动应用程序时选择哪些 jars 包含在类路径中
- php - 如何只用 wordpress 打标签
- selenium - Robotframework ctrl + space 不适用于 VS Code
- java - 将 spring-security-saml2-core 从 1.0.10.RELEASE 升级到 2.0.0.M31 时,Saml2 核心升级失败
- azure - 在 Docker 中运行的自定义 Azure DevOps 构建代理上具有卷装载的测试容器
- asp.net-mvc - VS2019:调试 mvc 代码以找到与按钮单击关联的控制器/动作
- wso2 - 存储 TRANSPORT_HEADERS 以在几次请求后恢复它们
- r - Sublime Text 显示 R 原生管道 |> 带有 Fira 代码的连字
- redis - 如何使用fluentd解析redis日志字段
- pdfbox - 如何使用 apache pdfBox 在 PDF 中编写表情符号?