khaled-dev / includable
帮助开发者通过在URL中输入类型名称来加载相关联的表格
v1.1.0
2017-11-28 14:44 UTC
This package is not auto-updated.
Last update: 2024-09-15 02:37:57 UTC
README
此软件包提供了一种简单的方法,通过在请求中引入来加载模型关系,如果您需要在请求中引入它,您必须确定要包含的关联关系
安装
使用Composer安装该软件包
$ composer require khaled-dev/includable
使用方法
首先在模型中使用特性
namespace App;
use Khaled7\Includable\Includable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Includable;
/**
* The attributes that are includable,
* references to a relations method.
*
* @var array
*/
protected $includable = [
'posts',
'votes',
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function votes()
{
return $this->hasMany(Vote::class);
}
// Not includable, coz not in $includable
public function subscribes()
{
return $this->hasMany(Subscribe::class);
}
}
控制器中
// Use to load all includable of all users
User::withRequestIncludes()->get()
// Use to load the includable of this instance
$user = User::first()
$user->loadRequestIncludes();
请求中
localhost:8000/users?includes=posts,votes
显示结果
// The method `loaded` comes with this package to easily load the included relation
// Use to load the model
$this->loaded('posts');
// Use to load the model to its laravel-resource
PostResource::collection($this->loaded('posts')),
// laravel-resource
// Use to Load an opptional model to its resource
PostResource::collection($this->when($this->loaded('posts'), $this->loaded('posts'))),
// laravel-resource
// Or semply you can use `WhenLoaded` laravel builtin method
PostResource::collection($this->whenLoaded('posts'))
建议使用laravel-resource
在结果中,它可以帮助您仅包含真正需要的关联,通常用于API。
许可证
MIT © Ben Constable 2017.