简体   繁体   English

Laravel获得所有具有关系的模型

[英]Laravel get all the models with relations

I can't find how to get all of the elements with relations to another element using Eloquent in Laravel. 我找不到如何在Laravel中使用Eloquent来获取与另一个元素相关的所有元素。 I have Substances and Contents and want all the contents related to the substances with name 'subst'. 我有物质和目录,并希望与名称为“ subst”的物质相关的所有目录。

My relation Substance - Content: 我的关系物质-内容:

public function relation () 
{
    return $this->belongsToMany('Substance', 'contents_substances', 'id_contents', 'id_substances');
}

public function relation () 
{
    return $this->belongsToMany('Content', 'contents_substances', 'id_contents', 'id_substances');
}

I know I can get all the contents related to one substance: 我知道我可以获得与一种物质有关的所有内容:

$content = Substance::find(1)->relation()->get();

but is possible to get all the contents related to a group of substances? 但是有可能获得与一组物质相关的所有内容吗?

something like: 就像是:

$sub = Substance::where('name', '=', 'subst'); // get all the substances with that name
$contents =$sub->relation()->get(); // ???

Any help is appreciated! 任何帮助表示赞赏!

The easiest is to start the query from the other angle. 最简单的方法是从另一个角度开始查询。 In this case from Content . 在这种情况下,来自Content whereHas will then add a constraint based on the substances relation: whereHas然后将添加一个基于约束substances关系:

$contents = Content::whereHas('substances', function($q){
    $q->where('name', 'subst');
})->get();

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

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