php 通过关系从 Laravel eloquent query 获取 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23239428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ID from Laravel eloquent query through a relationship
提问by Darren Craig
A company
hasMany users
, this relationship is achieved through a pivot table. I want to be able to get the company.ID
of the company an individual user is related to:
一个company
hasMany users
,这种关系是通过一个数据透视表来实现的。我希望能够获得与company.ID
个人用户相关的公司:
$company_id = User::find(Auth()->$id)->companies->get('$id');
Unfortunately, I have also tried the pluck()
method, but to no success. How can one retrieve a specific value from a formula like this?
不幸的是,我也尝试了该pluck()
方法,但没有成功。如何从这样的公式中检索特定值?
回答by Mohamed Bouallegue
in your user model you should add the relationship belongsTo (if the user belongs only to one company)
在您的用户模型中,您应该添加关系belongsTo(如果用户只属于一家公司)
public function company(){
return belongsTo('company');
}
then you can get the id of the company like this
然后你可以像这样获得公司的ID
$user = User::find($id);
$company = $user->company;
$companyId = $company->id;
I hope this will be helpful
我希望这会有所帮助
回答by Darren Craig
Well if the User can only be associated with one company, then your relationship should reflect this. Then you'd be able to use eager loading to do something like this:
好吧,如果用户只能与一家公司相关联,那么您的关系应该反映这一点。然后你就可以使用预先加载来做这样的事情:
// assumes the user is logged in
$user = Auth::user();
// assuming your relationship is set up correctly, you can do this:
echo $user->company->id;
You'd need to post the code relating to your models / relationships for a fuller answer, however.
但是,您需要发布与模型/关系相关的代码以获得更完整的答案。