【问题标题】:How to always append attributes to Laravel Eloquent model?如何始终将属性附加到 Laravel Eloquent 模型?
【发布时间】:2025-05-08 11:45:01
【问题描述】:

我想知道如何始终将一些数据附加到 Eloquent 模型而不需要询问它,例如在获取 Posts 表单数据库时我想将每个用户的用户信息附加为:

{
    id: 1
    title: "My Post Title"
    body: "Some text"
    created_at: "2-28-2016"
    user:{
            id: 1,
            name: "john smith",
            email: "example@mail.com"
         }
}

【问题讨论】:

    标签: php api laravel laravel-5 restful-architecture


    【解决方案1】:

    经过一番搜索,我发现您只需将所需的属性添加到 Eloquent 模型中的 $appends 数组即可:

     protected $appends = ['user'];
    

    更新:如果数据库中存在该属性,您可以根据下面的 David Barker's评论使用protected $with= ['user'];

    然后创建一个访问器为:

    public function getUserAttribute()
    {
    
        return $this->user();
    
    }
    

    这样,您始终可以将每个帖子的用户对象用作:

    {
        id: 1
        title: "My Post Title"
        body: "Some text"
        created_at: "2-28-2016"
        user:{
                id: 1,
                name: "john smith",
                email: "example@mail.com"
             }
    }
    

    【讨论】:

    • 您的用例有点奇怪,因为与User 的关系将使您无需使用附加即可使用$model->user。此外,当模型转换为 JSON 或转换为数组时,如果您已加载该关系,则 user 键将存在。如果您总是希望用户将protected $with = ['user']; 添加到模型中。
    • 是的,按照你的方式,我总是必须使用$model->user,但是我需要在没有手动请求的情况下拥有用户对象,此外我不想经历一个循环,我'我在 API 中使用它,所以当我显示文章列表时我无法获得它们。这样,用户对象将始终自动对您可用。
    • 不,不是当您添加protected $with = ['user'] 时,它会在您获取模型时自动为您加载。追加适用于您需要模型数据库中不可用的数据时。
    • 哦..我不知道。我会检查并更新我的答案。非常感谢。
    • 有一个包可以自动将访问器附加到响应github.com/topclaudy/eloquent-auto-append
    【解决方案2】:

    我发现这个概念很有趣,我学习和分享东西。 在此示例中,我附加了 id_hash 变量,然后通过此逻辑将其转换为方法,它采用第一个 char 并转换为大写,即下划线后的 Id 和字母,即大写,即 Hash。

    Laravel 本身添加了 getAttribute 将所有内容组合在一起它提供了getIdHashAttribute()

    class ProductDetail extends Model
    {
        protected $fillable = ['product_id','attributes','discount','stock','price','images'];
        protected $appends = ['id_hash'];
    
    
        public function productInfo()
        {
            return $this->hasOne('App\Product','id','product_id');
        }
    
        public function getIdHashAttribute(){
            return Crypt::encrypt($this->product_id);
        }
    }
    

    为了简化附加变量应该是这样的

    protected $appends = ['id_hash','test_var'];
    

    该方法将像这样在模型中定义

     public function getTestVarAttribute(){
            return "Hello world!";
        }
    

    【讨论】: