繁体   English   中英

Laravel Eloquent:如何在查询而不是模型中添加属性?

[英]Laravel Eloquent : how to add attribute at the query instead of in the model?

我需要将一些属性注入到一个雄辩的集合中,这些属性来自请求的模型中编写的函数。 因为我可以使用$appends属性,但直接在 eloquent 查询中。 类似Customer::with('orders_nb')->get()Customer::push('orders_nb')->all() 目标是能够使用这个新列对它们进行排序: Customer::orderBy('orders_nb)->get()

借助 ' $appends appends 属性检索 orders_nb :

class Customer extends Eloquent {
    protected $appends = array('orders_nb');

    public function getOrdersNbAttribute()
    {
        return $this->orders->count();  
    }
}

问题是我不想在所有雄辩的电话中检索这些属性。 这就是为什么我想在查询中注入这些额外的属性。

实际上,我正在使用自定义函数来获取带有这些额外数据的客户集合:

public static function allWithExtraAttr() {
    $foo = new Collection;
    foreach(Customer::all() as $customer) {
        $customer->orders_nb = $fonction->orders->count();
        $foo->push($fonction);
    }

    return $foo;
}

您认为有没有更好的方法来做到这一点?

一个小图来理解:如何在查询中而不是在模型中添加属性?

@geertjanknapen

我已经简化了解释的代码,但也有非关系函数, ::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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM