【问题标题】:How do I check for valid relationship between models in laravel如何检查 laravel 中模型之间的有效关系
【发布时间】:2016-12-12 21:10:45
【问题描述】:

我有一个 Group 模型,其中定义了多个关系。现在我想按各种参数浏览组。例如,一个组可以有一个“兴趣”,它被定义为模型中的关系。因此,如果我选择一个特定的兴趣,它应该显示所有相关的组。

public function browse(Request $request)
    {
        // $browseField is the field we are browsing against, $fieldId is the primary key for that relationship 
        // I want $browseField to be a valid relationship
        $browseField = $request->browseField;
        $fieldId = $request->fieldId;

        $groups = \App\Group::whereHas($browseField, function($q) use($fieldId) {
            $q->where('id', $fieldId);
        })->get();

        $data = ['groups' => $groups];
        return $this->sendResponseData($data);
    }

现在我不想为每个关系定义相同的过程,而是将关系名称作为参数。

现在,如果正确的 $browseField 是有效关系,则此方法有效。但是我如何检查这种关系是否真的存在。我应该以这种方式进行过滤还是有更好的方法?

编辑

为了更好地解释我想要做什么, 组有“年龄组”,“种族”等。如果我想按年龄组浏览,我会提供$browseField = ageGroupageGroup是关系),$browseField = ethnicity按种族浏览。现在,如果有人决定提供无效的$browseField = asfasf,代码会抛出错误。这就是我要防止的

【问题讨论】:

  • 听起来,你最好在你的兴趣模型中使用Interest::belongsToMany('Group');
  • 如果你正确地使用 MVC,你永远不需要检查模型类之间的连接,你明确地提供了。

标签: php laravel relationship


【解决方案1】:

您可以使用method_exists()

$group = new \App\Group();

if (method_exists($group, $browseField)) {
    $groups = $group->whereHas($browseField, function($q) use($fieldId) {
        $q->where('id', $fieldId);
    })->get();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2018-10-17
    • 2016-08-17
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多