简体   繁体   English

Laravel模型-抓取对象的ID

[英]Laravel Models - Grabbing Object's ID

I know that one can create an object from a model that represents a particular entry in the DB by using ModelName::find($model_id) . 我知道可以使用ModelName::find($model_id)从表示数据库中特定条目的模型创建对象。 What I'm curious about is how one goes about grabbing the current ID within the model on a function - so say that I wanted to expand the User model so that it will return all of the songs uploaded by said user. 我很好奇的是如何在函数上获取模型中的当前ID-可以说我想扩展User模型,以便它返回该用户上传的所有歌曲。

I want to just be able to call $user = User::find($user_id) to grab the relevant user, and then call the function from within the model like so: $user->list_songs() ;. 我只想能够调用$user = User::find($user_id)来获取相关用户,然后从模型内调用函数,如下所示: $user->list_songs() How do I, within this function in the model (public function list_songs()), check to see what the current id is? 我如何在模型中的该函数(公共函数list_songs())中检查当前的ID是什么? I'm currently passing it as a variable, and this seems counter-intuitive to the idea of a model. 我当前将其作为变量传递,这似乎与模型的想法背道而驰。

在模型内,只要将模型保存到数据库中,就可以简单地使用$this->id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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