Laravel - Eloquent - Dynamically defined relationship

前端 未结 4 748
广开言路
广开言路 2021-01-13 09:24

Is it possible to set a model\'s relationship dynamically? For example, I have model Page, and I want to add relationship banners() to it without a

4条回答
  •  爱一瞬间的悲伤
    2021-01-13 09:37

    Just in case anyone is looking for a Laravel 8 answer:

    Let's say I define my relationships in a single method of my model:

    public function relationships()
    {
        return [
            'user' => $this->belongsTo(User::class, 'user_id'),
        ];
    }
    

    Now, in my app service provider, I can use the resolveRelationUsing method. I've done this by iterating through the models folder and checking all models which contain the aforementioned method:

        foreach ((new Filesystem)->allFiles(app_path('Models')) as $file) {
            $namespace = 'App\\Models\\' . str_replace(['/', '.php'], ['\\', ''], $file->getRelativePathname());
            $class = app($namespace);
    
            if (method_exists($class, 'relationships')) {
                foreach ($class->relationships() as $key => $relationship) {
                    $class->resolveRelationUsing($key, function () use ($class, $key) {
                        return $class->relationships()[$key];
                    });
                }
            }
        }
    

提交回复
热议问题