【问题标题】:How to solve Laravel select queries conflicting with the $appends property on models?如何解决与模型上的 $appends 属性冲突的 Laravel 选择查询?
【发布时间】:2015-09-03 22:43:23
【问题描述】:

我有一种情况,我需要一个特定的属性访问器自动附加到我的模型之一:

class Mission extends Eloquent {  
    protected $appends = ['launch_date_time'];

    public function getLaunchDateTimeAttribute() {
        return ($this->attributes['launch_approximate'] == null) ? $this->attributes['launch_exact'] : $this->attributes['launch_approximate'];
    }
}

如您所见,这个 launch_date_time 属性依赖于我的模型的其他两个字段,这些字段实际上在我的数据库中。

但是,我现在想执行一个只返回一定数量字段的查询,因为这将通过 AJAX 多次发送,我宁愿使用尽可能少的资源:

// AJAX GET
// missions/all
public function all() {
    $allMissions = Mission::with('featuredImage')->get(['mission_id', 'name', 'featured_image']);
    return Response::json($allMissions);
}

这里的问题是我不再需要 launch_date_time 属性,所以我已经排除了它,**这样做,我的 AJAX 请求无法成功:

Undefined index: launch_approximate on line 78 of H:\myproj\app\models\Mission.php

这显然是因为我的模型试图附加launch_date_time,其中launch_approximate 是其依赖项。如果我包含所有必需的依赖项,那么所有我想要附加的属性都会出现:

$allMissions = Mission::with('featuredImage')->get(['mission_id', 'name', 'featured_image', 'launch_approximate', 'launch_exact', 'launch_date_time']);

这是不可取的。有没有可以保留两种设置的解决方案?

【问题讨论】:

    标签: php laravel orm eloquent


    【解决方案1】:

    它不起作用的原因是您没有在查询的get 方法中从数据库中检索必填字段。这就是您无法访问 launch_exactlaunch_approximate 的原因,因为它们没有在您的模型实例中设置。

    所以让它像你想要的那样工作。在访问它们之前,您必须检查是否设置了 launch_exactlaunch_approximate

    public function getLaunchDateTimeAttribute() {
        if(isset($this->attributes['launch_approximate']) && $this->attributes['launch_exact']) {
            return ($this->attributes['launch_approximate'] == null) ? $this->attributes['launch_exact'] : $this->attributes['launch_approximate'];
        } 
    
        return null;
    }
    

    您还可以在模型中设置带有$visible 属性的白名单和带有$hidden 的黑名单,以便在输出到json 或数组时不显示某些属性查看文档:http://laravel.com/docs/5.1/eloquent-serialization#hiding-attributes-from-json

    【讨论】:

    • 感谢队友帮助我! :)
    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多