jedrzej/withable

为 Laravel 的 Eloquent 模型提供的 Withable 特性

0.0.6 2019-09-05 08:10 UTC

This package is auto-updated.

Last update: 2024-09-05 19:05:39 UTC


README

本包为 Laravel 4/5/6 添加了使用请求参数动态预加载 Eloquent 模型关系的能力。

您可能还会发现以下包很有用

  • Searchable - 允许使用请求参数过滤模型
  • Sortable - 允许使用请求参数对模型进行排序
  • Pimpable - 一个元包,结合了 Sortable、Searchable 和 Withable 行为

Composer 安装

将以下行添加到您项目中的 composer.json 文件中

"jedrzej/withable": "0.0.6"

或者在您项目的根目录下命令行运行以下命令

composer require "jedrzej/withable" "0.0.6"

设置 withable 模型

为了使 Eloquent 模型具有 withable 功能,将特性和定义一个可以使用请求参数预加载的关系列表添加到模型中。您可以通过定义 $withable 属性或实现 getWithableRelations 方法来执行一些逻辑以定义可加载的关系列表。

use Jedrzej\Withable\WithableTrait;

class Post extends Eloquent
{
	use WithableTrait;
	
	// either a property holding a list of loadable relations...
	protected $withable = ['owner', 'forum'];
	
	// ...or a method that returns a list of loadable relations
	protected function getWithableRelations()
	{
		return ['owner', 'forum'];
	}
}

为了使所有关系可加载,请在列表中放置一个星号 *

protected $withable = ['*'];

加载关系

WithableTrait 为模型添加了一个 withRelations() 范围 - 您可以传递一个关系列表来加载,就像传递给 Eloquent 的 with() 方法一样

// return all posts with the user who created them and forum where they were posted
Post::withRelations(['owner', 'forum'])->get();
// return all posts with the user who created them
Post::withRelations('owner')->get();

或者它将使用 Request::all() 作为默认值。在 URL 中,您可以通过 with 参数传递要加载的关系列表或单个关系

// return all posts with the user who created them and forum where they were posted by appending to the URL
?with[]=owner&with[]=forum
// return all posts with the user who created them
?with=owner
//and then calling
Post::withRelations()->get();

加载范围关系

如果您在相关模型中定义了本地范围,您可以使用应用了该范围的关联来加载此关系。例如,为了预加载帖子及其已批准的评论

// define local scope in Comment model
public function scopeApproved($query) {
  $query->whereIsApproved(true);
}

// append the following to the URL in order to load "comments" relation with "approved" local scope applied
?with=comments:approved

// load the posts in your controller
Post::withRelations()->get();

附加配置

如果您正在使用 with 请求参数用于其他目的,您可以设置模型中的 $withParameterName 属性来更改将作为要加载的关系列表解释的参数名称,例如

protected $withParameterName = 'relations';

如果您需要执行一些额外的逻辑来定义要加载的关系列表(例如权限检查),您可以在模型中实现 getWithRelationsList() 方法并使其返回关系列表

public function getWithRelationsList() {
  return Request::get('relations');
}