[英]Laravel Eloquent : how to add attribute at the query instead of in the model?
I need to inject into an eloquent collection some attributes coming from functions written in the model requested.我需要将一些属性注入到一个雄辩的集合中,这些属性来自请求的模型中编写的函数。 As I could use the $appends
attribute, but directly in the eloquent query.因为我可以使用$appends
属性,但直接在 eloquent 查询中。 Something like Customer::with('orders_nb')->get()
or Customer::push('orders_nb')->all()
.类似Customer::with('orders_nb')->get()
或Customer::push('orders_nb')->all()
。 The goal is to be able to sort them with this new column : Customer::orderBy('orders_nb)->get()
目标是能够使用这个新列对它们进行排序: Customer::orderBy('orders_nb)->get()
Retrieve orders_nb thanks to the ' $appends
attribute :借助 ' $appends
appends 属性检索 orders_nb :
class Customer extends Eloquent {
protected $appends = array('orders_nb');
public function getOrdersNbAttribute()
{
return $this->orders->count();
}
}
The problem is that I don't want to retrieve theses attributes in all of my eloquent calls.问题是我不想在所有雄辩的电话中检索这些属性。 That's why I would like to inject these extra attributes in the query.这就是为什么我想在查询中注入这些额外的属性。
Actually I'm using a custom function to get my Customers collection with these extra data :实际上,我正在使用自定义函数来获取带有这些额外数据的客户集合:
public static function allWithExtraAttr() {
$foo = new Collection;
foreach(Customer::all() as $customer) {
$customer->orders_nb = $fonction->orders->count();
$foo->push($fonction);
}
return $foo;
}
Is there a better way to do it in your opinion?您认为有没有更好的方法来做到这一点?
A little diagram to understand : how to add attribute at the query instead of in the model ?一个小图来理解:如何在查询中而不是在模型中添加属性?
@geertjanknapen @geertjanknapen
I've simplified my code for the explications, but there is also non-relationship functions, which aren't recognized by ::with() function :我已经简化了解释的代码,但也有非关系函数, ::with() 函数无法识别:
public function getEmploisAttribute()
{
$emplois = new Collection();
foreach($this->fonction_sous_groupes as $fonction_sous_groupe) {
foreach($fonction_sous_groupe->emplois as $emploi) {
$emplois->push($emploi);
}
}
return $emplois;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.