Laravel 获取所有有关系的模型

Laravel get all the models with relations

我找不到如何使用 Laravel 中的 Eloquent 获取与另一个元素相关的所有元素。 我有物质和含量,想要与名称为 'subst'.

的物质相关的所有内容

我的关系物质 - 内容:

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');
}

我知道我可以获取与一种物质相关的所有内容:

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

但是有没有可能得到一组物质相关的所有内容呢?

类似于:

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

感谢任何帮助!

最简单的是从另一个角度开始查询。在这种情况下来自 ContentwhereHas 然后将根据 substances 关系添加约束:

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