[英]Common model_id for two Models - Laravel 5 - Eloquent
I have a question that I'm looking for its answer for a while. 我有一个问题,我正在寻找答案一段时间。 Well, in my Laravel Project, I have a Model
Disease
which has a belongstoMany relationship with Recipe
and User
Models. 好吧,在我的Laravel项目中,我患有一种模型
Disease
,该Disease
与Recipe
和User
Models属于属多关系。 I'm looking to fetch from database all recipe rows that have same disease_id as the current logged user . 我希望从数据库中获取与当前登录用户具有相同disease_id的所有配方行。 Is there any way to do so with Eloquent?
有没有办法用口才呢? Thank you !
谢谢 !
Would something like this work: 这样的事情会做:
$user = Auth::user();
return Recipe::where('disease_id', $user->id)->get();
Make sure your User
model has a diseases
relation defined: 确保您的
User
模型定义了diseases
关系:
public function diseases()
{
return $this->hasMany(Disease::class);
}
You can get the current user and disease_id
like this (edited to use the diseases relation on the Users model): 您可以像这样获取当前用户和
disease_id
(已编辑以在Users模型上使用disease_id
关系):
$user = Auth::user();
$disease_ids = $user->diseases()->pluck('id');
Then you can find the recipes with the same disease_id
like this: 然后,您可以找到具有相同
disease_id
的食谱,如下所示:
return Recipe::whereIn('disease_id', $disease_ids)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.