Laravel 5.1急切加载-带有参数的belongsToMany [英] Laravel 5.1 Eager Loading - belongsToMany with parameter

查看:55
本文介绍了Laravel 5.1急切加载-带有参数的belongsToMany的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有这种关系:

I have this relationship in my Model:

public function modulesData($module) {
    return $this->belongsToMany($module)
        ->withTimestamps();
}

我想要的是渴望加载我的模型的动态关系.但是我该怎么办呢?我使用此代码来渴望加载我的关系,但是如何添加参数 $ module ?

What I want is to eagerload a dynamic relation of my model. But how can I do this? I use this code to eagerload my relation, but how can I add the parameter $module?

$model->with(['modulesData'])->get();

感谢您的答复.

推荐答案

请考虑以下内容:

为模型定义后备功能:

public function __call($name, $arguments)
{
    if (strpos($name, 'modulesData') !== false) {
        $nameArray = explode(' ', $name);
        $moduleName = ucfirst($nameArray[1]);
        $moduleClass = 'App\Modules\\' . $moduleName . '\\' . $moduleName;
        return $this->modulesData($moduleClass);
    } else {
        return parent::__call($name, $arguments);
    }
}

通过以下方式使用 with 函数:

Use the with function with this way:

$tal = \App\Model::with('modulesData ModuleName')->get();

("ModuleName"是要用作关系参数的模块的名称).

(being 'ModuleName' the name of the module you want to use as parameter for the relationship).

通过这种方式,您可以加载字符串" modulesData_moduleName ".调用 with 时,它将找不到该函数,并将回退到 __ call ,后者将提取"moduleName"并使用它作为参数调用关系"modulesData".

This way you can eagerload with the string "modulesData_moduleName". When with is invoked it won't find that function and will fallback to __call, which will extract the "moduleName" and call the relationship "modulesData" with it as parameter.

这篇关于Laravel 5.1急切加载-带有参数的belongsToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆