aciddose/laravel-request-relationships

此包已被废弃且不再维护。未建议替代包。

这是一个Laravel模型Trait,允许您通过定义请求参数来自动加载模型的关系

dev-master 2017-10-28 11:21 UTC

This package is not auto-updated.

Last update: 2023-12-14 15:07:19 UTC


README

Laravel-request-relationships 提供了一个模型Trait,用于Laravel,当在请求中定义关系时可以自动加载模型的关系。加载的关系在URL中以与加载Eloquent关系相同的格式定义,例如 http://www.example.com/api/article/1?with=author,comments,comments.author

要求

此包需要PHP >= 7.0且支持Laravel >= 5.0。它可能适用于任何Eloquent实现,但尚未官方支持

安装

Laravel-request-relationships 以composer包的形式分发。您可以通过将其添加到composer.json文件中来安装它

"require": {
  "aciddose/laravel-request-relationships": "*"
}

如果您想自定义URL查询参数名称,请将服务提供程序添加到config/app.php配置文件中的providers数组中

Aciddose\RequestRelationships\ServiceProvider::class,

然后运行以下命令以创建配置文件

php artisan vendor:publish --provider=Aciddose\\RequestRelationships\\ServiceProvider

然后打开config/requestrelationships.php并更改default_parameter_name为所需的任何内容。

使用方法

该包提供了一种特质,您需要将其添加到任何希望自动加载工作的模型中。

use \Illuminate\Database\Eloquent\Model;
use \Aciddose\RequestRelationships\Traits\RequestRelationships;

class Article extends Model {
    use RequestRelationships;
    
    /**
     * Parameter name can be defined optionally for each model. If it's not defined, the default
     * parameter name from configuration is used (or `with` if no configuration is defined)
     */
    $requestRelationsParamName = 'with';

    public function author() {
        return $this->belongsTo('App\Users', 'user_id', 'id');
    }
}

定义了特质(假设您有一个正常工作的路由)后,您只需在请求中定义关系即可

http://www.example.com/api/article/1?with=author,comments,comments.author