Laravel5.7的一些用法
1、事件需要运行
php artisan queue:work
2、数据库对象关联
1对1 hasOne
1对多 hasMany
1依赖多 belongsTo
多依赖多 belongsToMany
3、
关联查询
with
关联统计
withCount
统计时指定字段名。
如:
withCount(['cardHolderOrders as order_count']);
4、
// 一次查询,判断昵称、手机号、会员ID 是否重复
if (!empty($id)) {
$checkName = AdminModel::query()->where('id', '<>', $id);
} else {
$checkName = AdminModel::query();
}
$checkName->where(function ($query) use ($nickname, $mobile, $memberId) {
$query->when($memberId , function ($q) use($memberId) {
$q->orWhere('member_id', $memberId);
})->when($nickname , function ($q) use($nickname) {
$q->orWhere('nick_name', $nickname);
})->when($mobile , function ($q) use($mobile) {
$q->orWhere('mobile', $mobile);
});
});
查出结果后,还需要再依次判断,是哪一个字段重复了。
例如:
if($checkName->first()){
$user = $checkName->first();
// 判断昵称
if($user['nick_name'] == $nickname) {
throw new ApiException("昵称已存在");
}
// 判断手机号
else if($user['mobile'] == $mobile) {
throw new ApiException("手机号已存在");
}
// 判断成员关系
elseif(!empty($memberId) && $user['member_id'] == $memberId) {
throw new ApiException("已绑定其他用户");
}
}
5、
怎样无侵入的限制用户针对某个数据表的访问权限。
#新建全局作用域,放到namespace对应文件夹里。
<?php
namespace App\Scopes;
/**
* 用于 无侵入式过滤 权限。
*/
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class DynamicShopFilterScope implements Scope
{
protected $searchColumn;
protected $ids;
public function __construct($searchColumn, $ids)
{
$this->searchColumn = $searchColumn;
$this->ids = $ids;
}
public function apply(Builder $builder, Model $model)
{
if (!empty($this->ids)) {
$builder->whereIn($this->searchColumn, $this->ids);
}
}
}
#新建中间件,放到namespace对应文件夹里。
<?php
namespace App\Http\Middleware;
/**
* 用于控制哪些功能,需要 后台用户的权限。
*/
use App\Scopes\DynamicShopFilterScope;
use Closure;
class ApplyShopFilter
{
public function handle($request, Closure $next)
{
$ids = request()->input('tokenInfo')['ids'];
// 添加用于过滤的全局作用域
// 某列表
YourModel::addGlobalScope(
new DynamicShopFilterScope('id', $ids)
);
// 某列表
YouTwoModel::addGlobalScope(
new DynamicShopFilterScope('shop_id', $ids)
);
return $next($request);
}
}
在需要限制的功能的路由中,加上中间件。
这样,对应功能中,对应Model的所有操作就会加上限制了。