Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

php - Laravel, how to ignore an accessor

I have a model with a custom accessor so I get that custom attribute,

    class Order extends GSModel{

        $appends = ['orderContents'];

        public function getOrderContentsAttribute()
        {
            return $this->contents()->get();
        } 
 }

But now, in one case, I need to get only some fields, without this OrderContents one.

$openOrders         = Order::open()->has('contents')->get(['id','date','tableName']);

But doing it this way, it returns me the OrderContents as well.. is there a way to not get that field?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Disappointing that people here gave you false information. There is in fact a built in method of achieving this, written straight into the IlluminateDatabaseEloquentModel class, called Model::getOriginal.

To retrieve the foo attribute, ignoring its accessor defined in Model::getFooAttribute, just call $myModel->getOriginal('foo');. This method is defined on line 3087 of IlluminateDatabaseEloquentModel.

Keep in mind that this method gets the original value on the model. This means that if you make any modifications to the attribute on that model instance, the above solution will not reflect those modifications. As long as you are just retrieving the value, you should have no problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...