Laravel 5.1 Eager Loading - belongsToMany with parameter

只谈情不闲聊 提交于 2021-02-07 10:58:23

问题


I have this relationship in my Model:

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

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();

Thanks for reply.


回答1:


Consider the following:

Define the fallback function to your Model:

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

Use the with function with this way:

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

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

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.




回答2:


I dont know how to pass parameters but you could do something like:

$model->with(['modulesData' => function($q) {
    $q->withTimestamps();
}])->get();


来源:https://stackoverflow.com/questions/34308434/laravel-5-1-eager-loading-belongstomany-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!