我想在服务关系中返回一个数组。在我的输出中,我想要这样的东西:
services: {
true: {...},
false: {...},
}
它自身的关系正在发挥作用。如果我只是
return $this->belongsToMany('AppService', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 1)
然后它工作得很好。但我想更深入。我希望services方法返回一个带有false和true键的数组。
像这里:
public function services()
{
return [
"true" => $this->belongsToMany('AppService', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 1),
"false" => $this->belongsToMany('AppService', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 0)
];
}
但我得到的是:
错误:调用数组上的成员函数addEagleConstraints((
我认为您在第二种方法中以错误的方式使用了laravel的关系特性。
例如,您可以在模型上定义两个关系函数,如下所示:
public function servicesIncluded()
{
return $this->belongsToMany('AppService', 'product_services', 'product_id', 'service_id')
->wherePivot('includes_it', 1);
}
public function services()
{
return $this->belongsToMany('AppService', '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('AppService', 'product_services', 'product_id', 'service_id')
->withPivot('includes_it');
}